2016-12-16 149 views
0

我有這個類定義的組件(之後由webpack和babel轉換回ES5)。我需要在其一種方法中使用$ http服務。我怎麼做?我在哪裏注入$ http作爲依賴項?如果我在構造函數參數中執行該操作,則會出現錯誤,好像我沒有注入它。也許上課不是這樣的嗎?如何在組件的類定義中注入依賴項?

angular.module('myApp').component('home', { 
    template: require('./home.component.html'), 
    controller: class HomeCtrl { 
     constructor() { 
     } 
     doMe() { 
      $http.get('http://www.yahoo.com/'); 
     } 
    } 
}); 

回答

1

ES2015類(或轉譯類)只是原型上的語法糖而不是原型繼承。這意味着你所定義的方法被放在「類」的原型上。爲了能夠訪問在構造函數中注入的依賴項,您需要以某種方式存儲它們以供以後通過原型方法引用。

function HomeController($http) { 
    this.$http = $http; 
} 
HomeController.prototype.doMe = function() { 
    this.$http.get('http://www.yahoo.com/'); 
}; 

在基於類的語法,這相當於:

class HomeController { 
    constructor($http) { 
    this.$http = $http; 
    } 

    doMe() { 
    this.$http.get('http://www.yahoo.com/'); 
    } 
} 

編輯:
如果你是

這通常是將它們放入實例來完成使用TypeScript,可以通過在構造函數參數上使用訪問修飾符來保存一些樣板文件。例如:

class HomeController { 
    constructor(private $http) {} 
} 

...這是簡寫:

class HomeController { 
    private $http; 

    contructor($http) { 
    this.$http = $http; 
    } 
} 

編輯2:
如果你想使你的控制器縮小友好的,你可以使用一個選項描述爲here(可能還有一個工具,如​​)。例如,這你怎麼可以用 「$inject屬性註釋」 的方法:

ES5

HomeController.$inject = ['$http']; 
function HomeController($http) {...} 
HomeController.prototype.doMe = function() {...} 

ES2015

class HomeController { 
    constructor($http) {...} 
    ... 
} 
HomeController.$inject = ['$http']; 

// OR 

class HomeController { 
    static get $inject() { return ['$http']; } 
    constructor($http) {...} 

    doMe() {...} 
} 

打字稿

class HomeController { 
    static $inject = ['$http']; 
    constructor(private $http) {} 

    doMe() {...} 
} 
+0

'靜態$注射= '$ HTTP']'可以也被添加。 – estus

+0

我沒有得到您的評論@estus:哪裏可以完全添加? – alexk

+0

@alexk在控制器類中。課程需要註明才能正確縮小。 – estus

0

類應該有明確的$inject註釋,以便正確地精縮到:

class HomeCtrl { 
    static get $inject() { 
     return ['$http']; 
    } 
    // or unstandardized shortcut: 
    // static $inject = ['$http']; 

    constructor($http) { 
     this.$http = $http; 
    } 

    doMe() { 
     this.$http... 
    } 
} 
0

最後,我所做的:

controller: class { 
    constructor($http, Restangular, $state) { 
     Object.assign(this, {$http, Restangular, $state}); 
    } 
    doMe() { 
     // use this.$http, this.Restangular & this.$state freely here 
    } 
}