2015-11-27 92 views
1

我使用AngularJS和打字稿,並得到ngSmoothScroll服務如下ngSmoothScroll從打字稿

/// <reference path="../includes.ts" /> 
declare function smoothScroll(element, options); 
module ScrollerSrvc{ 

    export interface IScrollerService{ 
     TopScroll(): any; 
    } 

    export class ScrollerService implements IScrollerService{ 
     static $inject = ['smoothScroll']; 
     TopScroll() { 
      var element = document.getElementById('scroller'); 

      var options = { 
       duration: 500, 
       easing: 'easeOutQuad', 
       offset: 0, 
       callbackBefore: function(element) { 

       }, 
       callbackAfter: function(element) { 

       } 
      } 
      smoothScroll(element, options); 
     } 
    } 
    function factory(): IScrollerService { 
     return new ScrollerService(); 
    } 
    angular.module('ScrollerSrvc', []).factory('ScrollerSrvc', factory); 
} 

,當我從我的控制器調用TopScroll是說沒有定義smoothScroll。

任何想法,爲什麼可能是這種情況?

回答

0

這裏有一些事情正在進行。

首先,雖然您的服務定義了$inject,但實際上並未將其注入課程中。您在當前代碼中有兩個錯誤。

1)你不要在你的ScrollerService定義構造函數,以節省您的smoothScroll注入依賴

export class ScrollerService implements IScrollerService{ 
    static $inject = ['smoothScroll']; 

    //The private keyword will automatically 
    // create a property of the same name on 
    // your class and assign it the parameter. 
    constructor(private smoothScroll){}  

    TopScroll() { 

     //...snip 

     this.smoothScroll(element, options); 
    } 
} 

2)要手動通過工廠函數,這意味着你將不會從角得到任何自動依賴注入創建一個新的服務實例。

要麼注入移動到工廠函數,並將其傳遞到您的服務:

function factory(smoothScroll): IScrollerService { 
    return new ScrollerService(smoothScroll); 
} 

//Functions are first class citizens in JS 
// so you can just add a $inject property 
factory.$inject = ['smoothScroll']; 

或者更好的是,完全拋棄了工廠函數因爲.service helper方法做,你在做什麼在這裏,除了它爲你處理注射。

//TypeScript is still just JS, so your class 
// is really just a function declaration at the 
// end of the day 
angular.module('ScrollerSrvc', []) 
    .service('ScrollerSrvc', ScrollerService); 

最後...

如果你想獲得注入的依賴,你可以定義一個函數定義的接口smoothScroll一些強類型,並在構造函數中使用它。

interface ISmoothScroll { 
    //Better would be to type these params as well 
    (element:any, options:any): void; 
} 

constructor(private smoothScroll: ISmoothScroll) {}