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. 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.

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. 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.

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.

How can I make canActivate wait for the helperValue subject to finish populating before executing the evaluation for the function?

1

There are 1 answers

0
AliF50 On

I would move it away from the guard's constructor (leave it empty) and make the canActivate run once the helperValue emits.

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.