问题
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