angularswitchmapcanactivate

Authorization Issue with Angular Auth Guard canActivate method


I am using an Angular authentication guard to handle authorization for each route. I need to call two API endpoints to retrieve user information and current user privileges. With my code, it follows the correct code path and prints the correct 'false' console log. However, I am getting 'true' as the output from the canActivate method. After debugging the code, I noticed that the subscribe method returns 'true' first, and then it executes the inner subscribe source. How can I fix this issue?

canActivate(route: ActivatedRouteSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
 
    return this.infuceService.getuser().pipe(
      map((response) => {
        const parsedResponse = typeof response === 'string' ? JSON.parse(response) : response;
        
        console.log("hshs: "+response)
        const editedResponse1 = {
          'userId': parsedResponse.userId,
          'partyRelationshipId': parsedResponse.partyRelationshipId
        };
        return editedResponse1;
      }),
      switchMap((editedResponse1: { userId: string; partyRelationshipId: string; }) =>
        this.infuceService.getprivilages(editedResponse1.userId, editedResponse1.partyRelationshipId)
      )
    ).subscribe((response2: any) => {
      if(response2.Endpoints.endpointFilterMap.hasOwnProperty("/test")){
            console.log('true');
              return true;
          }else {
            console.log('false');
            return false;
          }
    });

Solution

  • Instead of subscribing you should use map.

    map((response2: any) => {
      return response2.Endpoints.endpointFilterMap.hasOwnProperty("/test");
    })