Reputation: 1729
My goal is to use in-memory-web-api interchangeably with a real backend.
As stated in the Angular 2 (or 4) Tour of Heroes tutorial https://angular.io/tutorial/toh-pt6#extracting-the-data-in-the-then-callback :
Note the shape of the data that the server returns. This particular in-memory web API example returns an object with a data property. Your API might return something else. Adjust the code to match your web API.
The mocked web api service returns an object wrapped in a data attribute. The problem is that my backend doesn't return the data in that format, it doesn't have a "data" attribute.
.then(response => response.json().data as Hero[])
should be
.then(response => response.json() as Hero[])
and hopefully it should work. If I change it to the second version, the in-memory api doesn't work anymore...
Is there a way that I can change in-memory-web-api to actually remove that data attribute?
Upvotes: 2
Views: 4995
Reputation: 817
They have now made an option to choose whether to encapsulate the response with the data part or not.
HTTP response data no longer wrapped in object w/ data property
As of v0.5.0 (5 October 2017), the dataEncapsulation configuration default changed from false to true. The HTTP response body holds the data values directly rather than an object that encapsulates those values, {data: ...}.
In your app.module.ts, in the imports array you can use the dataEncapsulation flag to choose how you want to have it return:
HttpClientInMemoryWebApiModule.forRoot(
InMemoryDataService, { delay: 0, dataEncapsulation: false }
)
Upvotes: 2
Reputation: 3731
A slight tweak on @Ann's answer. I return multiple types of data from my IMDB so I needed to make it a little more generic:
import { InMemoryDbService, RequestInfo } from 'angular-in-memory-web-api';
import { ResponseOptions } from '@angular/http';
class AnyData{
data: any;
}
export class InMemoryDataService implements InMemoryDbService {
createDb() {
let myDataA = [{...}];
let myDataB = [{...}];
let myDataC = [{...}];
return { "A":myDataA,
"B":myDataB,
"C":myDataC };
}
protected responseInterceptor(res: ResponseOptions, ri: RequestInfo): ResponseOptions {
let wrapped:AnyData = <AnyData> res.body;
res.body = wrapped.data;
return res;
}
}
Upvotes: 2
Reputation: 186
Here's my solution for this:
import { InMemoryDbService, RequestInfo } from 'angular-in-memory-web-api';
import { ResponseOptions } from '@angular/http';
export class InMemoryDataService implements InMemoryDbService {
myData = 'any data';
createDb() {
let myData = this.myData;
return {myData};
}
protected responseInterceptor(res: ResponseOptions, ri: RequestInfo): ResponseOptions {
res.body = this.myData;
return res;
}
}
By default, in-memory-db would return {data: 'any data'} in it's body. In responseInterceptor you can change it to any type of data you want. Of course, this is very simplified version.
Upvotes: 6