質問

私の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;
      }]
    }
  });
}]);
.

ユーザーデータを取得するコードが複雑すぎる場合は、サービスを作成し、$routeProviderresolve関数でそのサービスを注入できます。

コントローラでは、約束(解決される予定)を注入するだけです。

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");   
 });
.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top