问题
I am trying to call google api for getting place suggestions from ember js. like below: this is the service module
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;
})
*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?
回答1:
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.
回答2:
The above approach doesnt work, so for any who wants to have maps suggestions on ember application , follow this https://www.npmjs.com/package/ember-cli-g-maps
It is perfectly working.
来源:https://stackoverflow.com/questions/47806350/response-undefined-when-calling-google-api-thru-emberjs