2016-04-24 43 views
0

目前我的代碼看起來是這樣的:有沒有一種方法可以等待angular-ui-router解決方案中的多個promise的結果?

resolve: { 
      adminTestLevel: ['testService', (tes: ITestService) => { 
       return tes.getAdminTestLevel(); 
      }], 
      adminTestStatus: ['testService', (tes: ITestService) => { 
       return tes.getAdminTestStatus(); 
      }], 
      adminTestType: ['testService', (tes: ITestService) => { 
       return tes.getAdminTestType(); 
      }], 
      adminTestGradeType: ['testService', (tes: ITestService) => { 
       return tes.getAdminTestGradeType() 
      }], 
      exams: ['testService', (tes: ITestService) => { 
       return tes.getExams(); 
      }], 
      examTypes: ['testService', (tes: ITestService) => { 
       return tes.getExamTypes(); 
      }], 
      testOrderBy: ['testService', (tes: ITestService) => { 
       return tes.getTestOrderBy(); 
      }], 
      topics: ['testService', (tes: ITestService) => { 
       return tes.getTestsTopics(); 
      }], 
     }, 

有沒有我可以簡化,這樣我就不必有ITestService這麼多的注射的方法嗎?此外,我不需要有所有不同的決議,如果可能的話,我想將它們合併爲一個。

回答

1

,你可以嘗試使用$q.all(promises)

從文檔

爲($q):

$q.all(promises);
將多個承諾到時所有的輸入承諾的決心,解決了單一的承諾。

因此,您可以在承諾數組中組合多個承諾並等待解決。你的代碼可能看起來像:

resolve: { 
    required_data: function($q, testService) { 
     return $q.all([ 
      testService.getAdminTestLevel(), 
      testService.getAdminTestStatus(), 
      testService.getAdminTestType() 

      // and so on for all other promises 
     ]) 
    } 
} 

然後在你的控制器,也從同一文檔

$q.all(promises)
返回一個承諾,將與值數組/哈希來解決,每個值對應的承諾在相同的索引/鍵在承諾數組/散列

您可以訪問從required_data注入到您的c ontroller。
例如adminTestLevel將在required_data[0] ...等等,以相同的順序,你已經在路由器中創建你的承諾陣列。

1

您可以使用$ q.all

resolve: { 
    myDate: function($q, tes) {  
     return $q.all([tes.getAdminTestLevel(), ... , tes.getTestsTopics()]); 
    } 
} 

myData只會在陣列中的所有承諾解決後才能解決

$q.all會給你結果的數組,你可以在你的控制器使用,你可以通過索引訪問它們,所以它不太方便,然後簡單的注入。

相關問題