簡體   English   中英

AngularJS UI路由器問題與解決

[英]angularjs ui-router issue with resolve

我正在使用angularjs和angular-ui-router創建一個基於狀態的路由應用程序。 我的應用程序中有幾條路線,但其中一條需要引起注意。 狀態定義如下

state('profile', {
            url: '/profile',
            controller: 'ProfileController', //controller on a different file
            resolve: {
                user_profile: ['User', function (User){
                    return User.getProfile(); //returns a json object
                }]
            },
            templateUrl: 'profile.html'
        })

getProfile代碼:getProfile:function(){var d = $ q.defer();

            $http.get('/profile')
                .success(function(res){
                    if (res.status == 'success'){
                        d.resolve(res);
                    } else {
                        d.reject();
                    }
                })
                .error(function(reason){
                    d.reject(reason);
                });
            return d.promise;
        }

現在在我的控制器文件中,有以下代碼:

.controller("ProfileController", ['$scope',function($scope,user_profile){
    console.log(user_profile);
}]);

問題是resolve應該將解析后的結果注入到名為user_profile的參數上的控制器中(因為在狀態定義的鍵中我使用了user_profile),並且注入的依賴項的值未定義,如console.log調用所述。

我已經調試了代碼,並且可以在服務器上獲取用戶配置文件的服務運行良好,因此,在那里沒有問題。 即使我在user_profile解析鍵上使用對象返回,該錯誤仍然存​​在。

另一件事是,如果我在狀態定義上將controller屬性設置為狀態定義中定義的函數,則將依賴項注入正確的值,但是我不希望這樣做,而是希望將依賴項注入到定義的內聯控制器上的controller no也是如此。

那么,這里會發生什么呢?

預先感謝您的任何答復。

您對angular使用嚴格的DI語法(依賴項名稱的字符串數組,該函數作為數組的最后一個參數),但尚未在數組中指定user_profile依賴項。

例如

.controller("ProfileController", ['$scope','user_profile',function($scope,user_profile) { console.log(user_profile); }]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM