问题描述:
在Angular中,HttpInterceptor用于拦截Http请求,并可以在请求发送前或响应返回后进行一些操作。然而,在登录后的第一个请求中,HttpInterceptor可能会无效,导致无法执行预期的操作。
解决方法:
一种解决方法是使用rxjs的tap操作符在登录后的第一个请求中手动触发拦截器。下面是一个代码示例:
import { Injectable } from '@angular/core';
@Injectable()
export class AuthService {
private isAuthenticated = false;
login() {
// 登录逻辑
this.isAuthenticated = true;
}
logout() {
// 登出逻辑
this.isAuthenticated = false;
}
getIsAuthenticated() {
return this.isAuthenticated;
}
}
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { AuthService } from './auth.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(req: HttpRequest, next: HttpHandler): Observable> {
if (this.authService.getIsAuthenticated()) {
// 在登录后的第一个请求中手动触发拦截器
return next.handle(req).pipe(
tap(
() => {},
error => {
// 在请求发生错误时进行处理
}
)
);
} else {
return next.handle(req);
}
}
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { AuthService } from './auth.service';
import { AuthInterceptor } from './auth.interceptor';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [
AuthService,
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {}
通过以上步骤,我们手动触发了HttpInterceptor,在登录后的第一个请求中也能正常执行预期的操作。