0
votes

I use the canActivate feature to protect some routes (admin). For this case I do use the an authGuard class/function:

The issue is, when I try to return an observable of boolean as: return Observable.of(false);, it doesn't work as expected and throws following Error:

Argument of type '(err: any) => Observable | Observable' is not assignable to parameter of type '(err: any, caught: Observable) => ObservableInput'. Type 'Observable | Observable' is not assignable to type 'ObservableInput'. Type 'Observable' is not assignable to type 'ObservableInput'. Type 'Observable' is not assignable to type 'ArrayLike'. Property 'length' is missing in type 'Observable'.

I have been searching and found kind of this issue, but not exactly the same. And the provided hint/solution was to use .throw(err);

When I change the return to: return Observable.throw(err);, then the error disappears, but it does not return false as It should be in order to protect my route.

I believe it's a type issue etc., but I just can't fix it, so that I keep returning observable.of(false)

canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean> | Promise<boolean> | boolean {
        return this.userService.getAdminAuth()
        .map( (res) => {
            if ( res === true) {
                return true;
            } else {
                ......
                return false;
            }
        })
        .catch( (err) => {
            if ( err.status === 403 ) {
                console.log(`403:  ${err.status}`);
                return this.userService.refreshToken()
                    .map( (res) => {
                        console.log(`Res RefreshToken: ${res}`);
                    });
            }
            return Observable.of(false); // protect route!
        });
}

Functions in user.service.ts:

....

isAdminAuthenticated = false;

public getAdminAuth() {
    console.log('Saved token: ' + localStorage.getItem('ac_token') );
    if ( this.isAdminAuthenticated === true ) {
        return Observable.of(true);
    } else {
        return this.http.get(
           'URL', { 
              headers: new HttpHeaders({"Accept": "application/json"}), 
              withCredentials: true, 
              observe: "response" 
           }
        )
        .map((res) => {
            if (res.status === 200) {
                this.isAdminAuthenticated = true;
                return true;
            } else {
                return false;
            }
        }, (err) => {
            console.log('Error: ' + err);
            return false;
        });
    }
}


refreshToken() {
    return this.http.get(
        'URL', 
        { 
            headers: new HttpHeaders(
                {
                    "Accept": "application/json",
                    "Authorization" : "Bearer " + localStorage.getItem('ac_token')
                }
            ), 
            withCredentials: true, 
            observe: "response" 
        }
    )
}

On the other hand, if I change refreshToken function to:

refreshToken() {
        return this._http.get(
            'URL', 
            { 
                headers: new HttpHeaders(
                    {
                        "Accept": "application/json",
                        "Authorization" : "Bearer " + localStorage.getItem('ac_token')
                    }
                ), 
                withCredentials: true, 
                observe: "response" 
            }
        ).map( (res) => {
            console.log(`Res: ${JSON.stringify(res)}` );
        }), (err) => {
            console.log(`Err: ${JSON.stringify(err)}` );
        };
}

Then the error says:

ERROR in src/app/admin.guard.ts(38,9): error TS2322: Type 'Observable' is not assignable to type 'boolean | Promise | Observable'. Type 'Observable' is not assignable to type 'Observable'. Type 'boolean | {}' is not assignable to type 'boolean'. Type '{}' is not assignable to type 'boolean'. src/app/service.guard.ts: error TS2339: Property 'map' does not exist on type '(err: any) => boolean'.

1
Shouldn't you also return false inside return this.userService.refreshToken() .map() in your catch? - Ashish Ranjan
No, unfortunately this doesn't fix the issue. Have been trying it. - k.vincent

1 Answers

1
votes

Because you're supposed to use return Observable.throw(false). of is a success, throw is an error.