我正在使用AngularJS和类型记录,并获得了如下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。
知道为什么会是这样吗?
发布于 2015-11-27 01:16:01
你这里有几件事要做。
主要是,虽然您在服务上定义了一个$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助手方法完全完成了您在这里所做的工作,只是它为您处理注入。
//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) {}https://stackoverflow.com/questions/33948867
复制相似问题