我和你有同样的问题。在使用in-memory-web-api 尝试覆盖类似于parseRequestUrl 的自述说明的post 方法之后,我并没有取得太大的成功;只是到了那里。
相反,我选择使用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,尤其是从 rxjs 导入的 Observable