gpt4 book ai didi

angular - 如何动态覆盖 Angular2 可注入(inject)服务?

转载 作者:行者123 更新时间:2023-12-02 09:26:15 25 4
gpt4 key购买 nike

我有一个可注入(inject)服务 HttpRequestService,当没有服务器时,我想用 MockHttpRequestService 替换它,因为我在开发模式下运行(npm start)。这个 MockHttpRequestService 将发回非常简单的响应。

我以为我找到了一种方法来动态替换我的 HttpRequestService,但不幸的是我看到 HttpRequestService 仍在使用中。这是我尝试过的:

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.
//...
}
}

最佳答案

您可以像这样在 Bootstrap 中使用 useClass 覆盖 Angular2 Service 可注入(inject)服务:

    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})
])

或直接在使用您的 http 服务的组件中
@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 !
}
}

我希望这个回复有帮助:)

关于angular - 如何动态覆盖 Angular2 可注入(inject)服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37821536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com