有没有办法从 antang.ts 文件中的 interceptor.service.ts 访问变量 角度 6 通用?



我需要将"this.cacheFlag"变量从interceptor.service.ts访问到我的应用程序的根目录中的server.ts文件中。

return next.handle(this.authReq).pipe(
tap((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
this.reqArray.push(event.status);
this.cacheFlag = true; //this is the variable I want to access in server.ts file
}
}),
catchError((error, caught) => {
//intercept the response error and displace it to the console
if (error instanceof HttpErrorResponse) {
if(error.url.indexOf("detail?referenceCode=") == -1){
this.reqArray.push(error.status);
this.cacheFlag = false; //this is the variable I want to access in server.ts file
}
})

尝试使用共享服务,然后订阅服务器中的值。 使用此代码创建共享服务

cacheFlag = new Observable<boolean>(false);
_cacheFlag = this.cacheFlag.asObservable();

nextValue(val) {
this.cacheFlag.next(val);
}

然后在 interceptor.ts 和 server.ts 的构造函数中添加此变量以及一个变量以分配从共享服务订阅的值

cf: boolean;
constructor( private ss: SharedService ) {
ss._cacheFlag.subscribe(value => this.cf = value)
}

然后最后在你的拦截器中。

return next.handle(this.authReq).pipe(
tap((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
this.reqArray.push(event.status);
this.ss.nextValue(true); //change this part
}
}),
catchError((error, caught) => {
//intercept the response error and displace it to the console
if (error instanceof HttpErrorResponse) {
if(error.url.indexOf("detail?referenceCode=") == -1){
this.reqArray.push(error.status);
this.ss.nextValue(false) //change this part
}
})

该值将在您的拦截器.ts和服务器.ts中更改 我希望这在某种程度上有所帮助。

将变量设为静态:

export class MyInterceptorService {
static cacheFlag;
intercept(...) {
...
if (MyInterceptorService.cacheFlag) {
// Cache
}
}
}

最新更新