我正在使用 angular 6 从事电子商务工作,但遇到以下问题。
我正在使用拦截器为请求设置自定义标头。此自定义标头是存储在 LocalStorage 中的哈希,由 CartService 提供。
我还有一个 AuthService ,它带有一个 observable ,它会发出用户是否登录。
在 CartService 中,它使用依赖注入接收 AuthService 并订阅该 observable 以查看用户是否登录,并在用户登录或退出时从后端重新加载购物车。
问题是:当我在拦截器中注入 CartService 时,会出现死循环,因为 CartService 的构造函数再次运行,因此购物车被重新加载,并发出请求,因此拦截器再次运行。但是, CartService 不应该是一个单例,它的构造函数应该只运行一次吗?
注意: CartService 和 CartHttpService 都带有 @Injectable({providedIn:'root'}) 注释
代码 :
购物车服务:
export class CartService {
private http: CartServiceHttp;
constructor(http: CartServiceHttp,
auth_service: AuthService) {
auth_service.isLogged().subscribe( (is_logged: boolean) => this.loadCart());
}
loadCart() {
this.http.getCart().pipe(
tap( (resp) => {
if (resp.hash) {
localStorage.setItem('CH', resp.hash);
}
this.loaded_cart = true;
}))
.subscribe( (resp) => {
this.cart_subject.next(new Cart(resp));
});
}
}
CartHash拦截器:
@Injectable()
export class CartHashInterceptor implements HttpInterceptor {
constructor(private cart_service: CartService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const hash = this.cart_service.getCartHash();
request = request.clone({
headers: request.headers.set('Cart-Hash', hash)
});
return next.handle(request);
}
购物车服务Http
Injectable({
providedIn: 'root'
})
export class CartServiceHttp {
private http: HttpClient;
constructor(http: HttpClient) {
this.http = http;
}
getCart(): Observable<Cart> {
const url = environment.cart_url + '/cart';
return this.http.get<Cart>(url)
.pipe(take(1));
}
}