代码之家  ›  专栏  ›  技术社区  ›  Hearen

angular模拟服务器响应数据的更好方法?

  •  1
  • Hearen  · 技术社区  · 7 年前

    我目前正在研究 组件库 这将取决于不同的服务器。

    我正在创建一个使用组件库的演示应用程序,以便可以轻松地捕获所有请求 interceptors 以此模拟服务器响应 demo 我创造了。

    限制

    • 组件本身将处理请求(组件用户将只传入关键参数);
    • 不允许修改组件库;

    现实

    • 服务器有时无法访问;
    • 制作一个演示应用程序来演示如何使用组件实际上并不需要与服务器进行实际的交互;

    但我还是很好奇:有没有其他方法来处理这类案件?

    大多数时候,我听说拦截器过去 修改 请求/响应(有时缓存)而不是模拟 .

    谢谢:)

    2 回复  |  直到 7 年前
        1
  •  1
  •   Amir    7 年前

    在这种情况下,可以使用JSON数据。您可以将JSON数据保存在一个文件中,并在拦截器处拦截您的请求,然后从如下文件发送模拟数据。

    @Injectable()
    export class SampleInterceptor implements HttpInterceptor {
      constructor(private http: HttpClient) {}
      intercept(
        request: HttpRequest<any>,
        next: HttpHandler
      ): Observable<HttpEvent<any>> {
        const httpRequest = new HttpRequest(
          <any>request.method,
          "./../../assets/sample.json"
        );
        request = Object.assign(request, httpRequest);
        request = request.clone();
        return next.handle(request);
      }
    }
    
        2
  •  0
  •   Saddam Pojee    7 年前

    你可以安装 json-server 然后使用它的模拟数据。

    npm install -g json-server
    

    创建 db.json 文件和一些数据

    {
      "posts": [
        { "id": 1, "title": "json-server", "author": "typicode" }
      ],
      "comments": [
        { "id": 1, "body": "some comment", "postId": 1 }
      ],
      "profile": { "name": "typicode" }
    }
    

    启动JSON服务器

    json-server --watch db.json
    

    现在如果你去 http://localhost:3000/posts/1 ,你会得到

    { "id": 1, "title": "json-server", "author": "typicode" }
    

    参考: https://github.com/typicode/json-server