我的角度应用程序中有一个post方法,它有一个空体。内存中的web api一直给出null没有item.id错误,但是如果我传递{}而不是null它就可以了。
我不想更改我在内存中的web api测试的实际调用,所以想知道是否有任何方法使我的内存web api不尝试添加任何内容或转换null至 {}。基本上我的post方法除了ping服务器之外没什么用呢
答案 0 :(得分:0)
我遇到了和你一样的问题。在使用in-memory-web-api尝试覆盖类似于post
的自述说明的parseRequestUrl
方法后,我没有取得多大成功;只是在那里分道扬。
相反,我选择使用Angular HttpInterceptor
,这似乎是现在回顾的逻辑决定。
创建一个检查空POST主体的HTTP拦截器类。如果找到,请将请求克隆为it should be considered immutable,并将正文设置为空对象{}
。如果有POST主体,则继续正常处理请求。然后导入AppModule
中的拦截器并包含在模块providers
数组中。
创建文件http-post-interceptor.ts
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest
} from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class HttpPostInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// if request body is falsey
if (!req.body) {
// clone immutable request and set empty POST body
const request = req.clone({ body: {} });
// continue with our modified POST request
return next.handle(request);
}
// else continue with the unmodified POST
return next.handle(req);
}
}
将HttpPostInterceptor
和HTTP_INTERCEPTORS
导入app.module.ts
// ...
import { /*...*/ HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpPostInterceptor } from './http-post-interceptor';
// ...
@NgModule({
// ...
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: HttpPostInterceptor, multi: true }
],
// ...
})
这就是它的全部内容。
这解决了我在当地环境中遇到的问题所以我不再收到你问题中提到的错误。
在生产版本中停用
由于in-memory-web-api
通常是非生产工具,因此您可能希望在生产版本中将其排除。通过导入environment
设置并检查生产属性是true
还是false
来执行此操作。这可以根据您的需要在拦截器或模块中完成。下面的示例通过AppModule
显示此内容。
将environment
设置导入app.module.ts
// ...
import { environment } from '../environments/environment';
// ...
@NgModule({
// ...
providers: [
environment.production ? [] :
{ provide: HTTP_INTERCEPTORS, useClass: HttpPostInterceptor, multi: true }
]
// ...
})
注意:某些导入路径可能会因您的项目结构而异,如果您使用的是Angular 6,特别是来自Observable
的{{1}}