Angular2 RC BaseRequestOption Constructor Injectio

2019-02-26 21:55发布

I don’t know whether I am missing something but injecting the constructor of a custom baserequestoptions class was working fine for me in Beta 17 but after moving to RC1 this approach doesn’t seem to work any more.

I have created a plunkr to illustrate that the webapibaseurl now comes through as undefined (the same code approach but with Beta 17 references worked):

https://embed.plnkr.co/usOljRDLap9RlLd3RIBd/

Any ideas?

2条回答
虎瘦雄心在
2楼-- · 2019-02-26 22:08

Extending from RequestOptions instead of from BaseRequestOptions made it work for me

@Injectable()
export class AppRequestOptions extends RequestOptions {
  constructor(@Inject('webApiBaseUrl') private webApiBaseUrl:string) {
    super({method: RequestMethod.Get, headers: new Headers()});
    console.log('webApiBaseUrl', webApiBaseUrl);
  }

  merge(options?:RequestOptionsArgs):RequestOptions {
    options.url = this.webApiBaseUrl + options.url;
    console.log('merge - options.url = '+options.url);
    return super.merge(options);
  }
}

otherwise for some unknown reason injecting @Inject('webApiBaseUrl') private webApiBaseUrl:string didn't work.

Plunker example

查看更多
老娘就宠你
3楼-- · 2019-02-26 22:21

This still works for me. Here is the custom option class I used:

import {BaseRequestOptions, RequestOptions, RequestOptionsArgs} from '@angular/http';

export class AppRequestOptions extends BaseRequestOptions {
  constructor() {
  }

  merge(options?:RequestOptionsArgs):RequestOptions {
    options.url = 'https://www.test.org' + options.url;
    return super.merge(options);
  }
}

and I register it this way:

bootstrap(App, [
  HTTP_PROVIDERS,
  provide(RequestOptions, {useClass: AppRequestOptions})
]);

See this plunkr: https://plnkr.co/edit/MK30JR2qK8aJIGwNqMZ5?p=preview.

Edit

It seems that there is a problem at the level of dependency injection for such class. I opened an issue: https://github.com/angular/angular/issues/8925.

查看更多
登录 后发表回答