2016-05-09 76 views
2

我的狀態如下:「invocables」必須是一個對象

.state('core.recover', { 
    url: '/recover', 
    controller: 'RecoverPasswordCtrl', 
    templateUrl: 'views/tmpl/recoverAccount/recover-password.html' 
}) 

我想,當我進入到這個狀態裝載模板,在這種情況下,之前檢查的東西我想調用的API如果承諾成功,則檢查是否會繼續並顯示模板,否則會將用戶重定向到另一個狀態。

我試圖做到這一點在控制器的頂部,但我總是看到模板了一會兒,然後將其重定向我,所以我試圖用決心,在這個崗位:

AngularJS | handle routing before they load

由於以下:

.state('core.recover', { 
     url: '/recover', 
     controller: 'RecoverPasswordCtrl', 
     resolve: function(recoverAccountService, $location, $state, $q) { 
      var deferred = $q.defer(); 
      deferred.resolve(); 
      recoverAccountService.get({email:$location.search().email, verificationKey:$location.search().verificationKey}) 
      .$promise.then(function (result) {}).catch(function (err) { 
      $state.go("candidature.pre"); 
      }); 
      return deferred.promise; 
     }, 
     templateUrl: 'views/tmpl/recoverAccount/recover-password.html' 
     }) 

,但它沒有工作,我得到這個錯誤在瀏覽器的控制檯:

Error: 'invocables' must be an object 

我該如何解決這個問題?

回答

1

您沒有使用正確的語法,uiRouter正在期待作爲resolve的輸入項,它將嘗試評估哪個鍵。

讓您的縮寫解析功能爲aimadResolver,這樣

var aimadResolver = function(recoverAccountService, $location, $state, $q) { 
    var deferred = $q.defer(); 
    deferred.resolve(); 
    recoverAccountService.get({ email: $location.search().email, verificationKey: $location.search().verificationKey }) 
     .$promise.then(function(result) {}).catch(function(err) { 
      $state.go("candidature.pre"); 
     }); 
    return deferred.promise; 
} 

當然,這不是強制性的,但我這樣做是爲了可讀性的原因。然後,你的狀態定義應該如下:

state('core.recover', { 
    url: '/recover', 
    controller: 'RecoverPasswordCtrl', 
    resolve: {'yourResolverName': aimaidResolver} 
    }, 
    templateUrl: 'views/tmpl/recoverAccount/recover-password.html' 
}) 

不要忘記在RecoverPasswordCtrl注入yourResolverName,否則你的控制器將無需等待反正被實例化。來源:look for the resolve examples

在我想指出的是您的延期對象的使用沒有意義的一側 。您立即在函數內的第二行解析延遲對象,這意味着recoverAccountservice.get()可能仍在等待處理,而RecoverPasswordCtrl已被實例化。假設recoverAccountservice.get()返回一個承諾(如果沒有,你應該改變它,使得它),你可以更有效地寫:

var aimadResolver = function(recoverAccountService, $location, $state, $q) { 
    return recoverAccountService.get({... }) 
     .then(function(result) { 
      // do nothing? Apparently you only want to $state.go on a rejection of the promise 
     }) 
     .catch(function(err) { 
      $state.go("candidature.pre"); 
      return $q.when() 
     }) 
} 

更多關於使用$q.when()deferred可以發現here

相關問題