首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular2 -将POST与angular-in-memory-web-api配合使用

Angular2 -将POST与angular-in-memory-web-api配合使用
EN

Stack Overflow用户
提问于 2017-03-07 00:15:43
回答 1查看 4K关注 0票数 5

我正在使用Angular 2的angular-in-memory-web-api,到目前为止,我只使用GET调用,它工作得很好。

我将要调用的API只使用POST调用,所以我开始将GET调用重写为POST调用,但随后它们停止返回模拟数据。在下面的测试函数中,我希望通过id将数据作为TestResponse对象获取:

代码语言:javascript
复制
postTest(id: string): Promise<TestResponse> {
    return this.http
        .post(this.testUrl, JSON.stringify({ testId: id }), { headers: this.headers })
        .toPromise()
        .then(response => response.json().data as TestResponse)
        .catch(this.handleError);
}

和模拟数据:

代码语言:javascript
复制
    let test = [
        { testId: 'e0d05d2b-3ec3-42ae-93bc-9937a665c4d6', missingData: 'qwerty', moreMissingData: 'asdfgh' },
        { testId: 'dccef969-b9cf-410a-9973-77549ec47777', missingData: 'qwerty', moreMissingData: 'asdfgh' },
        { testId: '20716fd7-1f50-4a12-af16-52c009bc42ab', missingData: 'qwerty', moreMissingData: 'asdfgh' }
    ];

如果我理解正确的话,这段代码将假设我想要创建一些东西,并因此使用id: 1弹回我的testId (它甚至不遵循我的数据结构)。

所以,我的问题是,我如何通过POST调用获得模拟数据?

EN

回答 1

Stack Overflow用户

发布于 2019-09-13 18:28:11

可以覆盖内存中数据服务实现中的HTTP方法。

在被覆盖的方法(例如POST)中,可以对集合名称做出反应(通过RequestInfo参数),以提供基于每个端点/集合的特定功能。

提供的一个示例仅处理GET调用:https://github.com/angular/in-memory-web-api/blob/master/src/app/hero-in-mem-data-override.service.ts

因此,覆盖POST功能可能如下所示:

代码语言:javascript
复制
import { InMemoryDbService, RequestInfo, STATUS, ResponseOptions } from 'angular-in-memory-web-api';

export class Your InMemoryDataService implements InMemoryDbService {

  // ...

  post(requestInfo: RequestInfo) {
    const collectionName = requestInfo.collectionName;
    if (collectionName === 'somedatatype') {
      // Intercept POST calls to the 'somedatatype' collection:
      // E.g. add some fields to our entity that would be set in the backend,
      const data = requestInfo.utils.getJsonBody(requestInfo.req);
      const collection = requestInfo.collection;
      data.extraField = 'hello';

      // set id to next highest number 
      data.id = collection.map(item => item.id).reduce((cur, next) => cur > next ? cur : next) + 1;

      // ... add the item to the collection
      collection.push(data);

      // forge the response
      const options: ResponseOptions = {
        body: { data  },
        status: STATUS.OK,
        headers: requestInfo.headers,
        url: requestInfo.url
      };

      // use createResponse$ to return proper response
      return requestInfo.utils.createResponse$(() => options);
    }

    // let the default POST handle all other collections by returning undefined
    return undefined; 
  }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42630421

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档