Angularjsで予想通り約束は約束しないのか
-
21-12-2019 - |
質問
私のangularjsアプリケーションでは、実行したページを変更するすべてのリクエストでのアプリケーションで:
$rootScope.$on('$locationChangeStart', function (event, next, current) {
var user;
$http.get('/api/Authentication/UserAuthenticated').then(function (data) {
console.log("call");
user = data.data;
});
console.log("end of call");
});
.
アプリケーションを実行してテストしたとき、私はConsoleで "Callの終了"がconsole.log("call");
の前に返されることを確認します。これは、ユーザーが設定されていないことを意味します。つまり、ルートユーザーの変更時にユーザーがログインしているかどうかを確認したい場合は未定義です。
どのようにAngular Run-> HTTPリクエストを行い、それだけに進みますか?
解決
質問を少し誤解しました。 resourtprovider $http
の約束を解決する:
var app = angular.module("myApp");
app.config(["$routeProvider", function($routeProvider) {
$routeProvider.when("/",{
templateUrl: "myTemplate.html",
controller: "MyCtrl",
resolve: {
user: ["$http", "$q", function($http, $q) {
var deferred = $q.defer();
$http.get('/api/Authentication/UserAuthenticated').success(function(data){
deferred.resolve(data.data);
}).error(function(error) {
deferred.resolve(false);
});
return deferred.promise;
}]
}
});
}]);
.
ユーザーデータを取得するコードが複雑すぎる場合は、サービスを作成し、$routeProvider
のresolve
関数でそのサービスを注入できます。
コントローラでは、約束(解決される予定)を注入するだけです。
app.controller("MyCtrl",["$scope","user", function($scope, user) {
if (!user) {
alert("User not found");
}
...
}]);
. 他のヒント
async:false
を使用します。私のために働いています
コードの代わりにこのコードを試してください
$rootScope.$on('$locationChangeStart', function (event, next, current) {
$http({method: 'GET',
url: '/api/Authentication/UserAuthenticated',
async: false
}).success(function (data) {
console.log("call");
user = data.data;
}
console.log("end of call");
});
. 所属していません StackOverflow