Angular 2 向服务注入复杂的服务

Angular 2 Inject complex service to service

我有三个服务和一个组件:

root.service 使用依赖注入对 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.serviceextend-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;
}

我想知道如何向 extend-child.service 注入一个对象,在本例中是 app.componentthis.num

谁能发现我做错了什么?

谢谢。

我还没有完全弄清楚你想要完成什么但是

   provide(AbstractChildService, { 
       useClass: ExtendChildService, 
       useValue: this.num})

不是有效的提供商。

您不能在一个提供程序中使用 useClass useValue 参数,一次只能使用一个。

您也不能在 @Component() 装饰器的提供程序中使用 this.。评估装饰器时,还没有 this. 可以引用的组件实例。

如果您想提供一个数字,您可以使用字符串或 OpaqueToken

provide('MyNumber', {useValue: 10}),

并由

注入
constructor(@Inject('MyNumber') private _num: number) { super(); }

另一种方法是使用工厂

provide(ExtendedChildService, {useFactory: () => { new ExtendedChildService(10)});

但是this.还是无法引用。