We are using Angular 2 in our projects. So far we use in-memory-web-api
in our data service in development:
app.module.ts:
imports: [
HttpModule,
InMemoryWebApiModule.forRoot(MockData),
...
]
data.service.ts:
constructor(private http: Http) { }
Now it's time to fetch some real data. However, we are not able to replace Mock Data all at once. How do I configure my data service to something like:
constructor(private fakeHttp: FakeHttp, /* this one use in-memory-api */
private http: Http /* this one goes to real remote server */) { }
so we can gradually move mock data out as project progresses?
Instead of trying to do this ugly "two HTTPs", the angular-in-memory-web-api
provides a couple of options.
Starting from 0.1.3, there is configuration property to forward all not-found collections calls to the regular XHR.
InMemoryWebApiModule.forRoot(MockData, {
passThruUnknownUrl: true
})
What this will do is forward any request for which it cannot find the collection, on to the real XHR. So one option is to just gradually remove collections from the in-memory db, as requried.
class MockData implements InMemoryDbService {
createDb() {
let cats = [];
let dogs = [];
return {
cats,
// dogs
};
}
}
Once you remove the dogs
collection from the DB, the in-memory will now forward all dog requests to the real backend.
This is just a collection level fix. But if you need even more granular control, you can use method interceptors.
In your MockData
class, say you want to override the get
method, just add it to the MockData
class, with a HttpMethodInterceptorArgs
argument.
class MockData implements InMemoryDbService {
get(args: HttpMethodInterceptorArgs) {
// do what you will here
}
}
The structure of the HttpMethodInterceptorArgs
is as follows (just so you have an idea of what you can do with it)
HttpMethodInterceptorArgs: {
requestInfo: {
req: Request (original request object)
base
collection
collectionName
headers
id
query
resourceUrl
}
passThruBackend: {
The Original XHRBackend (in most cases)
}
config: {
this is the configuration object you pass to the module.forRoot
}
db: {
this is the object from creatDb
}
}
As an example, here is what it would look like if you just forwarded all get requests
get(args: HttpMethodInterceptorArgs) {
return args.passthroughBackend.createConnection(args.requstInfo.req).response
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With