[英]Is there a way to access a variable from interceptor.service.ts in server.ts file in angular 6 universal?
I need to access the "this.cacheFlag" variable from interceptor.service.ts into server.ts file at the root in my application. 我需要从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 } })
Make your variable static : 将变量设为静态:
export class MyInterceptorService {
static cacheFlag;
intercept(...) {
...
if (MyInterceptorService.cacheFlag) {
// Cache
}
}
}
try using a shared service and then subscribing to the value in your server.ts for example create a shared service with this code 尝试使用共享服务,然后订阅服务器中的值。例如,使用此代码创建共享服务
cacheFlag = new Observable<boolean>(false);
_cacheFlag = this.cacheFlag.asObservable();
nextValue(val) {
this.cacheFlag.next(val);
}
and then in the constructor of your interceptor.ts and server.ts add this as well as a variable to assign the value being subscribed to from your shared service 然后在interceptor.ts和server.ts的构造函数中添加此变量以及一个变量,以分配从共享服务中订阅的值
cf: boolean;
constructor( private ss: SharedService ) {
ss._cacheFlag.subscribe(value => this.cf = value)
}
and then finally in your 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
}
})
the value will change in both your interceptor.ts and your server.ts I hope that helped in some way. 该值将在您的interceptor.ts和server.ts中都发生变化,我希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.