简体   繁体   English

如何防止 canActivate 在 Angular 防护的构造函数中完成 ReplaySubject 之前执行?

[英]How can I prevent canActivate from executing before a ReplaySubject finished in the constructor of the Angular guard?

I have a guard with a constructor similar to the snippet below.我有一个守卫,其构造函数类似于下面的代码片段。

//Constructor of my guard.ts file
constructor(
    private helperService: HelperService
) {
    this.helperService.replaySubjectProperty.subscribe(val => {
        this.helperValue = val;
    }
}

The HelperService.replaySubjectProperty is a ReplaySubject and the containing value is initialized within the constructor of HelperService . HelperService.replaySubjectProperty是一个ReplaySubject并且包含值在HelperService的构造函数中初始化。 Specifically, when the HelperService is initialized by the dependency injector, it has to get a value from the server and store it in the ReplaySubject .具体来说,当依赖注入器初始化HelperService时,它必须从服务器获取一个值并将其存储在ReplaySubject中。

Here's an example of the constructor of the service.这是服务构造函数的示例。

helperValue: ReplaySubject<int> = new ReplaySubject(1);

constructor(private http:HttpClient) {
    
    //This is a gross simplification of the process, but this code gets the point across.
    this.http<get>("getValue", {})
        .subscribe(result => this.helperValue.next(result);
}

Back in my guard, the canActivate method requires the data in helperValue to be populated.回过头来, canActivate方法需要填充helperValue中的数据。 In other words, the canActivate should not complete its evaluation until the server request initiated in the service constructor has completed and populated data in the helperValue replay subject.换句话说,直到在服务构造函数中发起的服务器请求完成并在helperValue重放主题中填充数据之前, canActivate不应完成其评估。

What I am seeing from within my Guard is that the constructor does call this.helperService.replaySubjectProperty.subscribe(...) as expected, however, the http<get> command in the constructor of the service has not completed, and the data has not yet been populated into the helperValue property.我在 Guard 中看到的是构造函数确实按预期调用this.helperService.replaySubjectProperty.subscribe(...) ,但是,服务构造函数中的http<get>命令尚未完成,并且数据尚未填充到helperValue属性中。

How can I make canActivate wait for the helperValue subject to finish populating before executing the evaluation for the function?在执行 function 的评估之前,如何让canActivate等待helperValue主题完成填充?

I would move it away from the guard's constructor (leave it empty) and make the canActivate run once the helperValue emits.我会将它从守卫的构造函数中移开(将其留空)并在helperValue发出后使canActivate运行。

Something like this:像这样的东西:

import { map } from 'rxjs/operators';
....
canActivate(): Observable<boolean> {
  return this.helperService.helperValue.asObservable().pipe(
     map(helperValue => /* The rest of your logic for true/false if the user can navigate */)
  );
}

That should wait until helperValue emits before proceed for true false.这应该等到helperValue发出,然后再继续为真假。

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

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