Search code examples
angularmockingxmlhttprequestbackend

Angular2 how to mock backend for development


I am writing an application in angular2 and I want to mock backend, which is just not ready at this point.

This is my service:

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import { Item } from './item';

@Injectable()
export class ItemService {

    private itemUrl = 'api/item';  // URL to web api

    constructor(private http: Http) { }

    getItems(): Observable<Item[]> {
        return this.http
            .get(this.itemUrl)
            .map(this.extractData)
            .catch(this.handleError);
    }

    addItem(name: string): Observable<Item> {
        let body = JSON.stringify({ name });
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post(this.itemUrl, body, options)
            .map(this.extractData)
            .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body.data || {};
    }

    private handleError(error: any) {
        let errMsg = 'error';
        return Observable.throw(errMsg);
    }
}

And I would like to intercept every request which is made to "itemUrl" in my TypeScript code and make simple operations on usual list.


Solution

  • You should probably use the angular-in-memory-web-api. See this post for an example. Also check out the documentation. In the long run, using this will probably save you more time than trying to use Angular's MockBackend. You can use the in-memory-web-api both for unit testing testing and development.