我创建了一个服务功能,该服务功能从API调用返回一个位置值toface Facebook Graph api
getLocation: function (access_token) {
return $http.get('https://graph.facebook.com/me?fields=location&access_token=' + access_token).then(function (response) {
console.log(response.data.location.name);
return response.data.location.name;
})
},
控制台日志返回我需要发送到我要在另一个函数中创建的对象的正确响应
createProfile: function (uid, user, credential) {
var profile = {
name: user.displayName,
email: user.email,
avatar: user.photoURL,
location: Auth.getLocation(credential.accessToken)
};
console.log(profile);
,但我在控制台上看到以下内容。当我只是想在getLocation Service的.then()响应函数中返回字符串时,它返回给我一个承诺对象。
控制台日志
问题是:因为$ http.get()。然后()是一个异步函数,因此您无法从中返回任何值。因此,这样您将永远无法获得价值。而且您也可以改进代码。
代码附加在下面:
服务代码:
getLocation: function (access_token, successHandler) {
$http.get('https://graph.facebook.com/me?fields=location&access_token=' + access_token).then(function (response) {
console.log(response.data.location.name);
successHandler(response.data.location.name);
})
}
控制器代码
createProfile: function (uid, user, credential) {
var profile;
function successHandler(response) {
profile = {
name: user.displayName,
email: user.email,
avatar: user.photoURL,
location: response
};
console.log(profile);
}
Auth.getLocation(credential.accessToken, successHandler);
}