How do I dynamically overwrite an Angular2 Injectable Service?

你离开我真会死。 提交于 2020-01-24 14:04:11

问题


I have an injectable service, HttpRequestService, which I would like replace with a MockHttpRequestService when there is no server because I'm running in development mode (npm start). This MockHttpRequestService will send back very simple responses.

I thought I'd found a way to dynamically replace my HttpRequestService, but unfortunately I see that HttpRequestService is still being used. Here's what I tried:

main.ts

import {bootstrap} from '@angular/platform-browser-dynamic';
import {provide} from '@angular/core';
import {ROUTER_PROVIDERS, Router} from '@angular/router-deprecated';
import {HashLocationStrategy, LocationStrategy} from '@angular/common'
import {Http, HTTP_PROVIDERS} from '@angular/http';
import {CORE_DIRECTIVES} from '@angular/common';
import {HttpRequestService} from './app/services/HttpRequestService';
import {MockHttpRequestService} from './app/services/MockHttpRequestService'
import {MyConfigInjectable} from './app/MyConfigInjectable';
import {SomeService} from './app/services/SomeService';

export function main(initialState?: any): Promise<any> {

    let providers = [
        ...HTTP_PROVIDERS,
        ...CORE_DIRECTIVES,
        ...ROUTER_PROVIDERS,
        provide(LocationStrategy, { useClass: HashLocationStrategy })
    ];

    if(process.env.ENV === 'development'){
        console.log('Is it set to development?'); //Yes. Yes it is.
        providers.push(MyConfigInjectable);
        providers.push(SomeService);
        providers.push(provide(HttpRequestService, {
            deps: [MyConfigInjectable, Http, SomeService, Router],
            useClass: MockHttpRequestService
        }));
    }

    return bootstrap(App, providers).catch(err => console.error(err));
}

MockHttpRequestService.ts

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {Router} from '@angular/router-deprecated';
import {SomeService} from './SomeService';
import {MyConfigInjectable} from '../MyconfigInjectable';

@Injectable()
export class MockHttpRequestService extends HttpRequestService {
    constructor(protected config: MyConfigInjectable,
                protected http: Http,
                protected someService: SomeService,
                protected router: Router) {
        super(config, http, someService, router);
    }

    post(url: string, body: string) {
        console.log('Are we getting here?'); //No. No we're not.
        //...
    }
}

回答1:


You can overwritte an Angular2 Service injectible service with useClass in bootstrap like that :

    import {provide} from '@angular/core';

    const IS_ENV_DEV = true; //Put this constant in your config maybe

    bootstrap(App, [
      provide(RaceService, {useClass: IS_ENV_DEV ? MockHttpRequestService : HttpRequestService})
    ])

Or directly in your Components which uses your http service

@Component({
   selector: 'my-comp',
   providers: [provide(HttpRequestService, {useClass: MockHttpRequestService})],
   template: `<strong>I use a mocked service</strong>`
})
export class MyComponent {

  constructor(private httpRequestService: HttpRequestService) {
    //Faker !
  }
}

I hope this response is helpful :)



来源:https://stackoverflow.com/questions/37821536/how-do-i-dynamically-overwrite-an-angular2-injectable-service

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