次は、名前、写真などのユーザープロファイルデータ用にMyAppのAPIにhttp要求を出して、navbarを更新するコードです。角度が更新されていないサービス変数
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:ヌル
プロフィール取得後: {"写真": "http://localhost:3000/img/1023.jpg"、 "名前": "Utkarsh Gupta"}
$ USERPROFILE:関数の先頭で定義されたプロファイルがnullであるので
$http.get()
が非同期であるとしてnull
最初の2つのログMSGのは明白です。しかし、$http.get()
関数が正常に返された後、プロファイルvarは3番目のログ・メッセージに示されているように更新されましたが、$userProfile
サービスは引き続きヌルになります。
$が角度の特定の変数のために予約されています...ユーザーのために$を使用することをお勧めは、私はすでに私が示されているコード内で宣言された変数を –