Angular2 RC BaseRequestOption Constructor Injection

╄→гoц情女王★ 提交于 2019-12-20 03:38:32

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/37549599/angular2-rc-baserequestoption-constructor-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!