I have implemented a project based on the "Tour of Heroes" tutorial. I have made it to the point where I want to start hitting my real REST backend, but ideally I'd just want to do this operation by operation.
I updated the post
call to use the URL for my REST service, as follows:
create(hero: Hero): Promise<Hero> {
return this.http
.post("http://127.0.0.1:3001/api/heroes", JSON.stringify(hero), {headers: this.headers})
.toPromise()
.then(res => return res.json().data)
.catch(this.handleError);
}
The problem is, this still just hits the InMemoryDbService
provided by the InMemoryWebApiModule
. In fact, it doesn't matter what the URL is I supply - as long as it ends in /heroes
, it works. I can put in any port number, any path, and any IP (as long as it is a parseable URL that ends in /heroes
).
I expected that the HttpModule
would work normally and the InMemoryWebApiModule
would only get hit when the URL resolved to the application's URL. Apparently this is not the case and somehow just having InMemoryWebApiModule.forRoot(InMemoryDataService)
in your module imports changes how Http
works (from what I can tell).
So my question is - is it possible to continue to use the InMemoryWebApiModule
to host mock services while you transition to a real service? How would you modify the "Tour of Heroes" tutorial to do this for a single operation?
You can pass options configuration object to the InMemoryWebApiModule.forRoot
. One of the configurations is passThruUnknownUrl
. Set that to true
, and it will use the normal XHRBackend
if the collection in the mock data can't be found
imports: [
InMemoryWebApiModule.forRoot(MockData, {
passThruUnknownUrl: true
})
]
So during you development, as new collections get created on the backend, you can start removing them on the front-end
createDb() {
let cats = [];
let dogs = [];
return {
cats,
// dogs
}
}
Originally, the in-memory would handle the URL /api/cats
and /api/dogs
. But lets say that the dogs
collection is now created on the backend. You can just remove dogs
from the above returned collections, and now the in-memory will forward those calls to the normal XHRBackend
so the XHR call is made.