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

时间:2018-10-25 06:41:52

标签: angular angular6 angular-universal ssr

我需要从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
        }
   })
      

2 个答案:

答案 0 :(得分:0)

将变量设为静态:

export class MyInterceptorService {
  static cacheFlag;

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

答案 1 :(得分:0)

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

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中的值都会改变 我希望这能有所帮助。