angular2 在构造函数中使用参数扩展服务

mau*_*rok 4 types angular2-services angular

我在理解如何在 angular2 中正确扩展服务时遇到了一些问题,可能是因为我不太了解如何在打字稿中扩展类。

超级班

@Injectable()
export class CallService{
    constructor(private errror:string){
        this.errMsg=errror;
    }
    private _errMsg:string;
    set errMsg(arg0:string){
        this._errMsg=arg0;
    }
    get errMsg():string{
        return this._errMsg;
    }
}
Run Code Online (Sandbox Code Playgroud)

子类

@Injectable()
export class DownloadService extends CallService{
    constructor(private error:string,private http:Http){
        super(error)
    }
}
Run Code Online (Sandbox Code Playgroud)

应用组件

@Component({
selector:'my-app',
    templateUrl:'app/app.component.html',
    styleUrls:['app/app.component.css'],
    directives:[ROUTER_DIRECTIVES,WaitComponent],
    providers:[DownloadService,SwitcherService,CallService,WaitService]
})
export class AppComponent{
    title:'App'
    constructor(
        private areadownloadservice:AreaDownloadService,
        private waitService:WaitService,
        private switcherservice:SwitcherService,
        private callService:CallService){}
    )
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是使用 CallService 扩展一些类,以便所有进行调用的类都有一个 errMsg 字符串属性来设置或获取,但我得到了这个异常:

没有 String 的提供者!

我错过了什么?

Gün*_*uer 5

你可以

  • 删除error参数

  • 使error参数可选

export class CallService{
    constructor(@Optional() private errror:string){

...

export class DownloadService extends CallService{
    constructor(@Optional() private error:string,private http:Http){
Run Code Online (Sandbox Code Playgroud)
  • 或者告诉 DI 它应该通过什么
bootstrap(AppComponent, [HTTP_PROVIDERS, {provide: 'someToken', useValue: 'someStringValue'}])
Run Code Online (Sandbox Code Playgroud)
export class CallService{
    constructor(@Inject('someToken') private errror:string){

...

export class DownloadService extends CallService{
    constructor(@Inject('someToken') private error:string,private http:Http){
Run Code Online (Sandbox Code Playgroud)

您还可以使用OpaqueToken代替字符串键 ('someToken')。
另见http://blog.thoughtram.io/angular/2016/05/23/opaque-tokens-in-angular-2.html