我正在使用Angular 2的angular-in-memory-web-api,到目前为止,我只使用GET调用,它工作得很好。
我将要调用的API只使用POST调用,所以我开始将GET调用重写为POST调用,但随后它们停止返回模拟数据。在下面的测试函数中,我希望通过id将数据作为TestResponse对象获取:
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);
}和模拟数据:
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调用获得模拟数据?
发布于 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功能可能如下所示:
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;
}
}https://stackoverflow.com/questions/42630421
复制相似问题