Search code examples
angularangular5angular2-routing

Subscription is not assigneable to type route


I am trying to set canActivate route but I am getting syntax error(Subscription is not assigneable to type route):

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const pin = route.paramMap.get('pin');
let canActivate;
if (pin) {
  return this.partService.getCached(pin).pipe(
     take(1),
     concatMap(p => { 
       if(this.appService.isUserAuthorized(Authorization.canAccessAll_View, p))
       { 
         return of(true);
       }
       return this.partService.getEnrolled(pin,'WW')
  })).subscribe(parts => {
        if(parts)
        {
          parts.forEach(part => {
            if (part.agencyCode == this.appService.user.agencyCode) {
              if (this.appService.isUserAuthorizedToView(part)) {
                canActivate = true;
              } else {
                this.routeToUnauthorized(state.url);
                canActivate = false;
              }

            }
          });
        } 
        return canActivate;       
  });      

}

}

What is wrong in the syntax here? Any help will be highly appreciated.


Solution

  • Instead of subscribing, try mapping. Like cghislai mentioned, you have to either return a boolean, Promise, or Observable;

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const pin = route.paramMap.get('pin');
    let canActivate = false; // initialize with a false value
    if (pin) {
      return this.partService.getCached(pin).pipe(
         take(1),
         concatMap(p => { 
           if(this.appService.isUserAuthorized(Authorization.canAccessAll_View, p))
           { 
             return of(true);
           }
           return this.partService.getEnrolled(pin,'WW');
      }),
      map(parts => {
        if(parts)
            {
              parts.forEach(part => {
                if (part.agencyCode == this.appService.user.agencyCode) {
                  if (this.appService.isUserAuthorizedToView(part)) {
                    canActivate = true;
                  } else {
                    this.routeToUnauthorized(state.url);
                    canActivate = false;
                  }
                }
              });
            } 
            return canActivate;
      }));
    }