简体   繁体   English

如何在angular2中模拟http.get

[英]How to mock an http.get in angular2

Let me explain. 让我解释。

I have this kind of request in "matiere.service.ts" 我在“ 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. 我想创建一个fakematiere.service.ts之类的虚假请求。 I'll lit to do it because the REST api I am connecting to is not coded yet. 我会照做的,因为我要连接的REST api尚未编码。 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. 我已经检查了“ in-memory-web-api”,但是我不知道它是否是正确的工具,但是,我真的不知道如何实现它。

Any help? 有什么帮助吗?

As per what @Rahul said, if you are only doing gets, a json file is quick and easy. 按照@Rahul所说的,如果您只是做gets,那么json文件又快又容易。

I have an example of using a json file here: https://github.com/DeborahK/Angular2-GettingStarted 我这里有一个使用json文件的示例: 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. 指向您的json文件。

But if you have put/post/etc, then in memory api is the way to go. 但是,如果您有put / post / etc,那么在内存中使用api是可行的方法。

I have an example of using in memory api here: https://github.com/DeborahK/Angular-Routing 我在这里有一个在内存中使用API​​的示例: https//github.com/DeborahK/Angular-Routing

I did use 我用过

npm install -g json-server

Work perfectly! 完美地工作!

Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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