【问题标题】:Is there a way to access a variable from interceptor.service.ts in server.ts file in angular 6 universal?有没有办法从 Angular 6 Universal 的 server.ts 文件中的 interceptor.service.ts 访问变量?
【发布时间】:2019-03-29 16:33:54
【问题描述】:

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

【问题讨论】:

  • 如何添加一个注入到interceptor.service.ts和server.ts的共享服务并在共享服务中设置标志?
  • 拦截器本身就是一个服务。问题是 server.ts 文件位于根级别(即 myapp/server.ts),所有服务(包括常用服务)都在里面(myapp/src/app/interceptor.service.ts)。
  • server.ts 是角度组件吗?该组件有什么特别之处吗? server.ts 和拦截器是否共享同一个模块?
  • 您可以从服务器提供一个对象并从您的拦截器修改其属性。您可以使用这里的响应对象来做到这一点:stackoverflow.com/a/49669873/1160794

标签: angular angular6 angular-universal server-side-rendering


【解决方案1】:

尝试使用共享服务,然后订阅 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)
}

最后在你的interceptor.ts

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 中的值都会发生变化 我希望这在某种程度上有所帮助。

【讨论】:

    【解决方案2】:

    将变量设为静态:

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

    【讨论】:

      猜你喜欢
      • 2019-03-16
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 2023-03-30
      相关资源
      最近更新 更多