简体   繁体   中英

how to use @CanActivate in angular 2

Im have a UserService and have A profile component, i have function in my Userservice and i want check if user is login the route can be active somthing like this :

@CanActivate((userService: UserService) => userService.checkLogin())

how to use CanActivate like this?

You can check if user login,

@Component({selector: ... })
@CanActivate(()=>console.log('Should the component Activate?'))
class AppComponent {

}

And go through CanActivate

@CanActivate() gets called before the Component is created, so you just have to return true or false in there if you want to route to the component or not.

import {appInjector} from './app-injector';
// ...
@CanActivate((next, prev) => {
    let injector = appInjector();
    let userService: UserService = injector.get(UserService);

    // if the checkLogin() method returns a boolean, you can just return it
    return userService.checkLogin();
}

You'll need a app-injector.ts to hold the current injector from bootstrapping:

let appInjectorRef;

export const appInjector:any = (injector = false) => {
    if (!injector) {
        return appInjectorRef;
    }

    appInjectorRef = injector;

    return appInjectorRef;
};

In your bootstrap call just store the injector:

import {appInjector} from './app-injector';
// ...
bootstrap(App, [
    [...],
    UserService
]).then((appRef) => appInjector(appRef.injector));

@CanActivate is a function decorator that takes one parameter that is a function. This function returns boolean or Promise. So you can use it like:

@CanActivate ((next, prev) => {
    return this.userService.checkLogin();
})

if your checkLogin() method returns Promise, eg,

return new Promise((resolve, reject) => {
    // some code...
    resolve(true);
});

Don't forget to inject your UserService through component constructor

export class MyComponent {
  constructor(private userService : UserService) { }
}

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