0

I have a multi module Angular2 application in which I need to mock some data providers (the endpoints don't exist yet).

I have a functioning MockBackend provider which I have tried injecting in:

  • the shared module that the data service resides in
  • the module that uses the data service
  • the component uses the data service

The first two resulted in the MockBackend taking over all http requests. The latter threw DI errors.

I could do with some guidance on how to inject separate instances.

Simon Stevens
  • 424
  • 1
  • 5
  • 13
  • 2
    Try [angular-in-memory-web-api](https://github.com/angular/in-memory-web-api). You can just [disable collections](https://stackoverflow.com/a/39864535/2587435) as they get implemented on the backend. – Paul Samsotha Aug 08 '17 at 08:06
  • Thanks for the pointer, this looks really useful and much easier to implement than MockBackend. I'm definitely going to look at using this. – Simon Stevens Aug 08 '17 at 08:11
  • Quick note, I'm still eager to discover how to inject separate instances – Simon Stevens Aug 08 '17 at 10:20
  • 1
    You can't for MockBackend because there is only one Http. You need to create a separate Https, using a different _token_ than `Http`. This means that you will be injecting two different Https (maybe Http and MockHttp), which you means you will have a lot of cleaning up to do when backend endpoints are done. – Paul Samsotha Aug 08 '17 at 10:43
  • If you're unsure what I mean by "token", see [this](https://angular.io/guide/dependency-injection#dependency-injection-tokens) or [this](https://stackoverflow.com/a/40019237/2587435) – Paul Samsotha Aug 08 '17 at 10:47
  • urgh, that's awful news.. thanks for the education though, it answers the problems I've been having – Simon Stevens Aug 08 '17 at 11:35
  • I don't want to say you _can't_, because you probably could. You could extend the MockBackend, passing the real XHRBackend to it and keep a reference to it. You can make the decision as to use mock data or send the real request. This is pretty much what the in-memory-api does, except it doesn't use the MockBackend, it uses its own custom backend. – Paul Samsotha Aug 08 '17 at 11:46

0 Answers0