简体   繁体   中英

How to mock an http.get in angular2

Let me explain.

I have this kind of request in "matiere.service.ts"

import { Injectable } from '@angular/core';
import {Http, RequestMethod} from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class MatiereService {
   private baseUrl = 'http://localhost:8080/tpFormation-web';

   constructor(private http: Http) { }

   list() {
        return this.http.get(`${this.baseUrl}/matiere`);
   }

   find(id) {
       return this.http.get(`${this.baseUrl}/matiere/${id}`);
   }
}

I would like to have something like a fakematiere.service.ts that is creating fake request. I'll lit to do it because the REST api I am connecting to is not coded yet. I have checked around "in-memory-web-api" but I don't know if it's the right tool and tho, I don't really know how to implement it.

Any help?

As per what @Rahul said, if you are only doing gets, a json file is quick and easy.

I have an example of using a json file here: https://github.com/DeborahK/Angular2-GettingStarted

Basically, you just need to change this line of code:

private baseUrl = 'http://localhost:8080/tpFormation-web';

To point to your json file.

But if you have put/post/etc, then in memory api is the way to go.

I have an example of using in memory api here: https://github.com/DeborahK/Angular-Routing

I did use

npm install -g json-server

Work perfectly!

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM