Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 extend service with argument in constructor

I have some problems in understanding how to extend correctly a service in angular2, maybe because I don't understand well how to extend a class in typescript.

SuperClass

@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;
    }
}

SubClass

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

App.Component

@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){}
    )
}

What I want to do is to extend some classes with CallService so that all class that make a calls will have a errMsg string property to set or get, but I get this exception:

No provider for String!

What did I missed?

like image 703
mautrok Avatar asked Mar 11 '23 11:03

mautrok


1 Answers

You can either

  • remove the error parameter

  • make the error parameter optional

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

...

export class DownloadService extends CallService{
    constructor(@Optional() private error:string,private http:Http){
  • or tell DI what it should pass
bootstrap(AppComponent, [HTTP_PROVIDERS, {provide: 'someToken', useValue: 'someStringValue'}])
export class CallService{
    constructor(@Inject('someToken') private errror:string){

...

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

You can also use an OpaqueToken instead of the string key ('someToken').
See also http://blog.thoughtram.io/angular/2016/05/23/opaque-tokens-in-angular-2.html

like image 77
Günter Zöchbauer Avatar answered Mar 19 '23 13:03

Günter Zöchbauer