以下是爲用戶配置文件數據(如名稱,照片)向MyApp的API發送http請求以更新導航欄的代碼。Angular not updating服務變量
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()
是異步的配置文件是空作爲函數的定義開始。但$http.get()
函數成功返回後,配置文件var得到更新,如第三次日誌消息中所示,但$userProfile
服務繼續爲空。
$保留給角特定變量...不是一個好的做法是使用$用戶做出變量 –