0
votes

I have an issue conerning my auth guard where I'm trying to call two async http request, and then after it's successfuly done I want to do a third one to get one last info before I let user access the page.

Here is my code so far :

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

    if (this.recruteurService.getUserInfo() &&
      this.recruteurService.getIndividuPro() &&
      this.recruteurService.getEtablissement()) {
      return true;
    }

    return forkJoin(
      this.recruteurService.rechercherUserInfo(),
      this.recruteurService.rechercherIndividuProfessionnel())
      .mergeMap(([userInfo, individuPro]) => {
        if (userInfo && individuPro) {
          this.recruteurService.setUserInfo(userInfo);
          this.recruteurService.setIndividuPro(individuPro);
        } else {
          return false;
        }

        return this.recruteurService.rechercherEtablissementParIdRce(individuPro.etablissements[0]).map(
          (etablissement: Etablissement) => {
            if (etablissement) {
              this.recruteurService.setEtablissement(etablissement);
              return of(true);
            }
            return of(false);
          });
      });
  }

The problem is that I'm getting an error :

ERROR in src/app/guard/initialization.guard.ts(32,17): error TS2345: Argument of type '([userInfo, individuPro]: [any, Individu]) => false | Observable>' is not assignable to parameter of type '(value: [any, Individu], index: number) => ObservableInput>'. Type 'false | Observable>' is not assignable to type 'ObservableInput>'. Type 'false' is not assignable to type 'ObservableInput>'.

But I can't figure out what's the problem.

2

2 Answers

1
votes

You defined canActivate() => boolean but then you're returning forkJoin() which is Observable<boolean> if I understand your code correctly.

The canActivate method can return boolean or Observable<boolean> thus boolean | Observable<boolean> return type, see https://angular.io/api/router/CanActivate.

You might want to make canActivate(...): boolean | Observable<boolean> or just use only canActivate(...): Observable<boolean> and then return return of(true);.

0
votes

Ok I managed to find a solution using the operator flatMap on the second observable stream :

return this.recruteurService.rechercherEtablissementParIdRce(individuPro.etablissements[0]).flatMap(

flatMap - It basically merges an observable sequence of observable sequences into a single observable sequence.

Thank to this doc : Map vs FlatMap