0

我有一个守卫,其构造函数类似于下面的代码片段。

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

HelperService.replaySubjectPropertyaReplaySubject并且包含值在 的构造函数中初始化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<get>服务构造函数中的命令尚未完成,并且数据尚未填充到helperValue属性中。

如何在执行函数评估之前canActivate等待主题完成填充?helperValue

4

1 回答 1

1

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

像这样的东西:

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发出真假之前再继续。

于 2021-05-07T20:30:12.153 回答