【发布时间】:2016-12-04 05:29:57
【问题描述】:
以下是向 MyApp 的 API 发出 http 请求以获取用户个人资料数据(如姓名、照片)以更新导航栏的代码。
var app = angular.module('MyApp', ['ng']);
app.controller('navBarController', function($scope, $userProfile) {
$scope.userProfile = $userProfile;
console.log("$userProfile: " + JSON.stringify($userProfile));
setTimeout(function() {
console.log("$userProfile: " + JSON.stringify($userProfile));
}, 3000);
});
app.factory('$userProfile', function($http) {
var profile = null;
$http.
get('/api/v1/me').
success(function(data) {
profile = data;
console.log("profile after get: " + JSON.stringify(profile));
}).
error(function(data, $status) {
if ($status === status.UNAUTHORISED) {
profile = null;
console.log("profile if error: " + JSON.stringify(profile));
}
});
console.log("profile (finally): " + JSON.stringify(profile));
return profile;
});
app.directive('navBar', function() {
return {
controller: 'navBarController',
templateUrl: 'templates/nav_bar.html'
}
});
我正在控制台日志记录以检查我得到的意外结果,日志如下:
个人资料(最终):空
$userProfile: 空
获取后的个人资料: {"photo":"http://localhost:3000/img/1023.jpg","name":"Utkarsh Gupta"}
$userProfile: 空
前两个日志消息很明显,因为 $http.get() 是异步的,因此配置文件为函数开头定义的 null。但是在$http.get() 函数成功返回后,profile var 得到了更新,如第三条日志消息所示,但$userProfile 服务仍然为空。
【问题讨论】:
-
$ 保留用于特定角度的变量...对于用户创建的变量使用 $ 不是一个好习惯
标签: javascript angularjs