2014-09-29 119 views
10

我一直在寫AngularJS應用程序一段時間,但是Typescript對我來說是新手,然後在AngularJS中添加到Typescript中與我用的有點不同。AngularJS和Typescript - 注入服務

不管怎麼說,就是兩者之間的區別是:

app.service('customerDataService', Application.Services.CustomerDataService);

app.service('customerDataService', ['$http', '$q', Application.Services.CustomerDataService]);

控制器TS

module Application { 
    export module Services { 
     export interface ICustomerDataService { 
      getCustomer(id: number): ng.IPromise<Models.ICustomer>; 
     } 

     export class CustomerDataService implements ICustomerDataService { 
      constructor(private $http: ng.IHttpService, private $q: ng.IQService) { 
      } 

      getCustomer(id: number): ng.IPromise<Models.ICustomer> { 
       return this.$http.get('data/Customer.json').then((response) => { 
        return response.data; 
       }); 
      } 
     } 
    } 
} 

應用TS

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

app.value('config', new Application.ApplicationConfig()); 

app.service('customerDataService', ['$http', '$q', Application.Services.CustomerDataService]); 
app.service('customerDataService', Application.Services.CustomerDataService); 

app.controller('DefaultController', ['$scope','config', 'customerDataService', Application.Controllers.DefaultController]); 

他們都似乎工作。你是否必須明確定義服務的注入?

+0

如果您沒有縮小或縮小,但使用[ng-annotate](https://github.com/olov/ng-annotate),則不一定需要注入依賴項。你也可以通過定義一個靜態'$ inject'屬性來定義服務類中的依賴項: - 'static $ inject = ['$ http','$ q']'。使用注入也可以讓你有時候使用更好的變量名稱......但是,如果你打開strict-di,你必須列出你的依賴。 – PSL 2014-09-29 22:27:28

+0

視頻教程:https://www.youtube.com/watch?v = Yis8m3BdnEM &hd = 1 – basarat 2014-09-29 23:35:48

回答

15

縮小代碼時,您確實需要爲服務或任何其他角實體(提供程序,工廠,控制器等)注入依賴項。在非縮減代碼中,兩種方法都可以工作。

考慮構造: -

constructor(private $http: ng.IHttpService, private $q: ng.IQService) { 
} 

案例1顯式依賴註釋]: -

app.service('customerDataService', ['$http', '$q', Application.Services.CustomerDataService]); 

在微小無問題,以及因爲即使minifier改變$httpa$qb它仍然會工作,因爲角將內部使用註釋來從您提供的定義服務的數組派生依賴項。

案例2暗指的依賴]: -

app.service('customerDataService', Application.Services.CustomerDataService); 

在如果$http是變化的說a$q改爲b角將尋找aProvider和bProvider在實例爲您服務,最終你這種情況下,應用程序在使用縮小文件運行時會失敗,因爲沒有任何內容被列爲依賴關係,因此角度分析器必須解析方法定義和方法的參數名稱才能發現依賴關係。

另一種注入依賴關係的方法是使用函數(cTor)(而不是實例)上定義的$inject屬性。你可以這樣做: -

export class CustomerDataService implements ICustomerDataService { 
     static $inject = ['$http', '$q']; //<-- Inject here 

     constructor(private $http: ng.IHttpService, private $q: ng.IQService) { 
     } 
     .... 

,只是: -

app.service('customerDataService', Application.Services.CustomerDataService); 

並上市的依賴有時也幫助注入的服務參數名稱中使用的替代名稱。如果你不想做所有這些,並且仍然可以使用縮小器來處理代碼,那麼可以使用ng-annotate庫。


隨着角1.3 RC,有一個名爲strict-di一個選項,你可以與你rootElement執行任何服務或將您的應用程序生命週期中實例化任何角度實體明確標註的依賴注入指定。如果您使用此選項以及任何未明確註釋的服務將在實例化過程中失敗。

0

都是一樣的,但在你的第一個選項縮小時,因爲微小的邏輯將改變依賴 的名稱,以便在第二個選項你給的依賴將縮小算法中不會觸及數組我們的代碼會被搗毀

相關問題