angular2 in-memory-web-api only for a part of an application

自闭症网瘾萝莉.ら 提交于 2019-12-11 06:04:37

问题


I was wondering if is possible to configure angular2 in-memory-web-api only for a part of an application. I want to reach external endpoints for finished components and use in-memory-web-api for components in development stage.

I've tried to do this in the folowing two ways:

1 - Loading the data in the main and changing the XHRBackend in the components that I want to reach in-memory endpoints;

main.ts

bootstrap(AppComponent, [
    ...
    { provide: SEED_DATA, useClass: InMemoryDataService }
]);

inDevelopmentStage.service.ts

@Component({
    providers: [
        { provide: XHRBackend, useClass: InMemoryBackendService }
    ]
})

2 - Loading the data and changing the XHRBackend in the components that I want to reach in-memory endpoints;

inDevelopmentStage.service.ts

@Component({
    providers: [
        { provide: XHRBackend, useClass: InMemoryBackendService }, // in-mem server
        { provide: SEED_DATA, useClass: InMemoryDataService }      // in-mem server data
    ]
})

Is there any way that I can achieve this goal?

Thanks for your help!


回答1:


As pointed by filipesilva here, the second way should work.

" Oh sure, you can definitely do this. Each component has it's own injector, which is what resolves providers for itself and all components in that subtree.

Your second example should have worked:

@Component({
    providers: [
        { provide: XHRBackend, useClass: InMemoryBackendService }, // in-mem server
        { provide: SEED_DATA, useClass: InMemoryDataService }      // in-mem server data
    ]
})

As for that component and it's subtree, XHRBackend is InMemoryBackendService instead of the service provided by HTTP_PROVIDERS.

Remember that it also applies to any other components in that subtree however. Maybe that's what was going wrong? "

Thanks Filipe!



来源:https://stackoverflow.com/questions/38637381/angular2-in-memory-web-api-only-for-a-part-of-an-application

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