繁体   English   中英

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

[英]Is there a way to access a variable from interceptor.service.ts in server.ts file in angular 6 universal?

我需要从interceptor.service.ts中将“ this.cacheFlag”变量访问到应用程序根目录中的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 } }) 

将变量设为静态:

export class MyInterceptorService {
  static cacheFlag;

  intercept(...) {
    ...
    if (MyInterceptorService.cacheFlag) {
      // Cache
    }
  }
}

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

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
        }
   })

该值将在您的interceptor.ts和server.ts中都发生变化,我希望这会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM