以下是一个使用Angular的HTTP请求管道和拦截器的示例:
http-interceptor.ts
的文件,并添加以下代码:import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
// 在发送请求之前做一些处理
console.log('Interceptor - Before Request:', req);
// 继续请求
return next.handle(req).pipe(
// 在响应返回之后做一些处理
tap(event => {
console.log('Interceptor - After Response:', event);
})
);
}
}
app.module.ts
)中引入和注册拦截器。添加以下代码:import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyHttpInterceptor } from './http-interceptor';
@NgModule({
imports: [
HttpClientModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MyHttpInterceptor,
multi: true
}
]
})
export class AppModule { }
HttpClient
来发起HTTP请求。添加以下代码:import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
template: `
`
})
export class AppComponent {
constructor(private http: HttpClient) { }
getData() {
this.http.get('https://api.example.com/data').subscribe(response => {
console.log('Response:', response);
});
}
}
使用这个示例,你可以自定义拦截器的逻辑,比如添加身份验证信息、错误处理等。