2016-03-02 16 views
0

我正在研究一個基於離子和角js的項目。我正在加載包含鍵值對中的一些JSON數據的JSON文件。我想要實現的是在json文件完全加載後,我必須調用$ urlRouterProvider.otherwise()方法。以下是我嘗試過的代碼,但它不適用於我。我試圖把控制檯放在'defaultRoute'函數中,但是'$ urlRouterProvider.otherwise'('/ tab/myjobs')'這行不起作用。下面的代碼在app.config函數中存在。任何幫助將不勝感激。

$.getJSON('js/constants/'+lang+'.json') 
     .then(function(response) { 
     $translateProvider.translations(window.localStorage['deviceLanguage'],response); 
     defaultRoute($urlRouterProvider); 
       }, function(response) { 
        //$translate.use('en'); 
     }); 


function defaultRoute($urlRouterProvider){ 
      if(window.localStorage['userData']) { 
     var access_token = JSON.parse(window.localStorage['userData']).access_token; 
     if(access_token){ 
      $urlRouterProvider.otherwise('/tab/myjobs'); 
     }else{ 
      $urlRouterProvider.otherwise('/login'); 
     } 
    }else{ 
     console.log("in line 282"); 
     $urlRouterProvider.otherwise('/login'); 
    } 
} 
+0

我不確定這是否可行,但您可以做的是在getJSON代碼周圍添加一個超時,以確保它首先運行。 –

+0

$ urlRouterProvider.otherwise無法在setTimeout函數 –

+0

中使用角度提供的'$ timeout'嗎? –

回答

0

考慮使用$state.go('someState')

你想你的代碼看起來像這樣:

if(access_token){ 
      $state.go('myJobs'); // where myJobs is the state correlated with your url 'tabs/jobs' 
     }else{ 
      $state.go('login'); // or whatever the state name is that you have for 'login' 
     } 
    }else{ 
     console.log("in line 282"); 
     $state.go('login'); 
    } 
+0

我試過使用$ state.go()。但它會給出錯誤'$ state is not defined'。 –

+0

你在你的控制器中定義了$ state嗎? – Rarepuppers

+0

我有app.config函數中的所有路由。我想在同一個函數中使用$ state。我可以使用它嗎? –

0

如果您嘗試有條件地將用戶以不同的路線,使用$state.go('route.path')而非更新.otherwise()配置。例如:

var app = angular.module('myapp',['ionic']); 

app.controller('$scope', '$state','$http', [function($scope, $state, $http){ 
    $http.get('my/api/path') 
    .then(function(response){ 
     if(response.authenticated){ 
      $state.go('secret.route'); 
     } else { 
      $state.go('public.route'); 
     } 
    }); 
}]); 
1

問題是,你是運行在配置階段異步方法。

AngularJS生命週期2階段被分裂,配置(在這裏你可以使用供應商,而不是服務,因爲這些尚未註冊),和運行(在這裏你不能用供應商,但你可以使用服務,一般相當於主要功能)。

當配置階段結束運行階段開始,並且配置相不等待任何異步過程,因此正在發生的事情是,當你的JSON得到承諾解決您的配置階段已經完成(所以你在你的承諾成功回調中嘗試做的任何提供者配置都沒有真正配置任何東西)。

簡而言之,不能使用$ urlRouterProvider.otherwise()傳遞異步調用的結果,如getJson方法。

一對夫婦替代你正在嘗試做(重定向用戶根據AUTH)是: angular ui-router login authenticationangularjs redirect to login page if not authenticated with exceptions

相關問題