通过emberjs调用google api时响应未定义 [英] response undefined when calling google api thru emberjs

查看:80
本文介绍了通过emberjs调用google api时响应未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试致电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()抛出不是函数,或者为什么responseundefined而不是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 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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆