我有三项服务和一个组件:
-
root.service
-
abstarct-child.service
-
extend-child.service
-
app.component
root.service
通过使用依赖注入(inject)来注入(inject) abstarct-child.service
,像这样:
import {Injectable} from 'angular2/core';
import {AbstractChildService} from './abstarct-child.service';
@Injectable()
export class RootService {
constructor(private _abstractChildService: AbstractChildService) {}
UseChildServiceDoSomethingFunction(){}
}
abstarct-child.service
看起来像这样:
import {Injectable} from 'angular2/core';
@Injectable()
export abstract class AbstractChildService {
abstract doSomething(): any ;
}
extend-child.service
看起来像这样:
import {Injectable} from 'angular2/core';
import {AbstractChildService} from './abstarct-child.service';
@Injectable()
export class ExtendChildService extends AbstractChildService{
constructor(private _num: number) { super(); }
doSomething() : any { return true; }
}
app.component
提供root.service
和 extend-child.service
如abstract-child.service
像这样:
import {Component} from 'angular2/core';
import {Input} from 'angular2/core';
import {provide} from 'angular2/core';
import {RootService} from './root.service';
import {AbstractChildService} from './abstarct-child.service';
import {ExtendChildService} from './extend-child.service';
@Component({
selector: 'app',
providers: [provide(AbstractChildService, { useClass: ExtendChildService, useValue: this.num})]
})
export class AppComponent {
@Input('given_Num') num: number;
}
我想知道如何注入(inject)extend-child.service
一个对象,在本例中为 this.num
的app.component
?
有人能发现我做错了什么吗?
谢谢。
最佳答案
我还没有完全弄清楚你想要完成什么,但是
provide(AbstractChildService, {
useClass: ExtendChildService,
useValue: this.num})
不是有效的提供商。
您不能在一个提供程序中同时拥有 useClass
和 useValue
参数,一次只能有一个。
您也不能在 @Component()
装饰器的提供程序中使用 this.
。当装饰器被评估时,还没有 this.
可以引用的组件实例。
如果您想提供一个数字,您可以使用字符串或 OpaqueToken
provide('MyNumber', {useValue: 10}),
然后将其注入(inject)
constructor(@Inject('MyNumber') private _num: number) { super(); }
另一种方法是使用工厂
provide(ExtendedChildService, {useFactory: () => { new ExtendedChildService(10)});
但是this.
仍然无法被引用。
关于typescript - Angular 2 将复杂的服务注入(inject)到服务中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36259119/