我正在为 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);
}
Run Code Online (Sandbox Code Playgroud)
和模拟数据:
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' }
];
Run Code Online (Sandbox Code Playgroud)
如果我理解正确,这段代码将假设我想创建一些东西,因此将我的 testId 与 id: 1 (它甚至不遵循我的数据结构)一起弹回。
所以,我的问题是,如何通过 POST 调用获取模拟数据?
可以在内存数据服务实现中覆盖 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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3848 次 |
| 最近记录: |