Search code examples
angulartypescriptrxjsangular2-services

Using subscription in router can activate in angular2/4 fails


Am trying to guard my routes but am getting an error that

Type 'Subscription' is not assignable to type 'boolean 
     | Promise<boolean> | Observable<any>'

so in the route guard have

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<boolean> | boolean {
     return this._authService.checkLoggedin().subscribe((res)=>{
     if(!res){
        console.log("res is not here..")
      }
      return res;

    },(err)=>{

     console.log("error is", err);
  })
 }   

So my authservice i have

  checkLoggedin(): Observable<any> {
    if (!this._accesstokenService.getToken('access_token')) {
      return Observable.of(false); //just checks for localstorage
     }
      //if the access token exists  validate it on the server
    return this._http.post(this.authurl + 'auth/is-loggedin', 1)
      .map((res) => {
       return Observable.of(res);
      });
 }

Where am i going wrong. I would still like to continue using the observable from checkloggedin method


Solution

  • You need to return an observable not a subscription in your canActivate

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<boolean> | boolean {
         return this._authService.checkLoggedin();
     }  
    

    Your return signature dictates it so, but if I were you I would make it return a boolean and keep it simple.