简体   繁体   中英

canActivate returns false and still goes to screen Angular 2

I`m having an issue where my canActivate method returns false and still navigates to blocked screen. This issues is only present in Chrome while in IE everything works as intended. canActivate method looks lke this:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.getDataFromApi(state.url)
        .toPromise()
        .then(result=> { 
            return result;
        });
}

And getDataFromApi() :

getDataFromApi(link): Observable<boolean> {
    return this.http.get("api/security")
                    .map(response => {
                        var url = link.replace("/", "");
                        var data = response.json();
                        var privileges = data["privileges"];
                        var currentItem = privileges[url];
                        return currentItem["view"];
                    });
}

Is there any way to resolve this issue in Chrome? Thanks is advance.

EDIT I've checked in IE, EDGE, Firefox where issue is non present. Chrome works only with developers console open.

This looks like an async problem to me.

In you guard you are returning return this.getDataFromApi(state.url) , then when this resolves, you are again trying to return return result; . This will mean your guard is actually returning Before you return result .

I recommend setting up a service for handling login and holding authentication state. This service could have properties like isLoggedIn: bool , roles: Role[] etc.

Then, in you guard, you simple check with the service if the user isLoggedIn (or something similar). If the user is authenticated, you return true, if not, you redirect him or her to a login page. If the user is logged in, check if the user got the correct roles (with the pre-loaded roles in the service), then return true or false accordingly.

Take a look at the official docs , they have a quite good example of this approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM