【问题标题】:How can I prevent canActivate from executing before a ReplaySubject finished in the constructor of the Angular guard?如何防止 canActivate 在 Angular 防护的构造函数中完成 ReplaySubject 之前执行?
【发布时间】:2021-05-08 04:30:12
【问题描述】:

我有一个守卫,其构造函数类似于下面的 sn-p。

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

HelperService.replaySubjectProperty 是一个ReplaySubject,包含值在HelperService 的构造函数中初始化。具体来说,当依赖注入器初始化HelperService时,它必须从服务器获取一个值并将其存储在ReplaySubject中。

这是服务构造函数的示例。

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

请注意,canActivate 方法需要填充 helperValue 中的数据。换言之,canActivate 不应完成其评估,直到在服务构造函数中发起的服务器请求完成并在 helperValue 重播主题中填充数据。

我在 Guard 中看到的是构造函数确实按预期调用了 this.helperService.replaySubjectProperty.subscribe(...),但是,服务构造函数中的 http&lt;get&gt; 命令尚未完成,数据尚未填充到helperValue 属性。

如何让canActivate 等待helperValue 主题完成填充,然后再执行函数评估?

【问题讨论】:

    标签: angular rxjs angular-guards


    【解决方案1】:

    我会将它从守卫的构造函数中移开(将其留空)并在helperValue 发出后让canActivate 运行。

    类似这样的:

    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 */)
      );
    }
    

    这应该等到helperValue 发出,然后再继续为真假。

    【讨论】:

      猜你喜欢
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多