How to use the Angular In-Memory Web API .data attribute?

Viewed 4363

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?

3 Answers

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;
    }
}
Related