是的,您可以通过使用HttpInterceptor来实现这一点。HttpInterceptors 允许您直接返回响应而不是将其发送到服务器,在将请求发送到服务器之前修改请求(URL、正文、标头等)和/或修改从服务器返回的响应。
例如,如果请求 url 匹配 /my/path,则以下拦截器返回响应而不进行服务器调用。它还修改了请求
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.url === '/my/path') {
// If request matches a certain url, do not call server and return result from angular
return of(new HttpResponse({
body: '{x: 1, y: 2}',
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
status: 200,
}));
}
if (req.url === '/my/other/path') {
// if request matches a certain url, modify the request before sending it to the server
req = req.clone({
setHeaders: {
'X-MY-CUSTOM-HEADER': 'value'
},
});
}
// Pass the request to the next interceptor, if there are none, then the server is called.
const result = next.handle(req);
return result.pipe(
map((response) => {
// modify response from server here
return response;
}),
);
}
}
要使用拦截器,请通过提供 HTTP_INTERCEPTORS 将其添加到应用程序模块中,如下所示:
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule,
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: MyHttpInterceptor, multi: true},
],
bootstrap: [AppComponent]
})
export class AppModule { }