通过emberjs调用google api时响应未定义 [英] response undefined when calling google api thru emberjs
问题描述
我正在尝试致电google API,以从ember js获取位置建议.如下所示:这是服务模块
fetch(){
let url=`https://maps.googleapis.com/maps/api/place/autocomplete/json?input=IL&types=geocode&key=API_KEY`
return Ember.RSVP.resolve(Ember.$.ajax(url,{
method: 'GET'
}))
.then(
(response)=>{
console.log("google suggested places:",response);
return response;
})
*上面的网址与API_KEY一起提供并粘贴在浏览器中时,将返回JSON响应以及建议的位置.
此外,我在开发人员工具的newtwork标签中看到JSON响应,但是.then无法捕获该响应,并在控制台中以未定义的响应打印.
ref: https://developers.google.com/places/web -service/autocomplete#place_autocomplete_results
在控制台中,我看到无法加载 https://maps.googleapis.com/maps/api/place/autocomplete/json?input=IL&types=geocode&key=API_KEY :否'Access-control-Allow_origin '请求的资源上存在标头.因此,不允许访问源' http://localhost:4200 ./p>
我在做什么错了?
您正在使用 jQuery.ajax()
的别名.但这应该返回一个 jqXHR
对象.所以我不知道为什么您的代码没有为Ember.$ajax()
抛出不是函数,或者为什么response
是undefined
而不是jqXHR
对象.
但是,您将ajax调用包装在promise中的方法是错误的.我还要说使用jQuery.ajax并不是最佳实践.正在进行一些工作以使ember.js中的jQuery成为可选的,并且您不希望将应用程序与之耦合.
我建议使用 ember-fetch 或 *the above url when served with API_KEY and pasted in browser, a JSON response is returned with the suggested places. also, i am seeing JSON response in newtwork tab of developer tools but the .then is not able to capture that resonse, and printing in console as response undefined. ref : https://developers.google.com/places/web-service/autocomplete#place_autocomplete_results And in console i am seeing " Failed to load https://maps.googleapis.com/maps/api/place/autocomplete/json?input=IL&types=geocode&key=API_KEY: No 'Access-control-Allow_origin'header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. What am i doing wrong? You are using But nevertheless your approach to wrap the ajax call in a promise is wrong. Also I would say using jQuery.ajax is not best practice. There are some work ongoing to make jQuery optional in ember.js and you don't want to couple your application with it. I would recommend using ember-fetch or ember-ajax. 这篇关于通过emberjs调用google api时响应未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!Ember.RSVP.resolve
wrong. It returns a Promise
which resolves immediately with value passed as first argument. So in your case it resolves with return value of Ember.$ajax()
. I'm not quite sure if this function exists. I guess you meant Ember.$.ajax()
which is just an alias for jQuery.ajax()
. But this one should return a jqXHR
object. So I have no idea why your code is not throwing for Ember.$ajax()
is not a function or why response
is undefined
and not a jqXHR
object.