How to use AngularJS 1.5 component router in combination with user authentication?

I'm not quite ready to upgrade to Angular 2, but I wanted to tackle their new router and components.

For the background, I use a Python instance in the Google App Engine, which uses Endpoints along with Angular.

How to use AngularJS 1.5 component router to serve html with and without authenticated user? I want to make this as Angular as possible. Current documentation is lost for me.

+4
source share
1 answer

Recently, I struggled with the same. I solved it like this:

In the component definition object, add the $ canActivate property:

import { MainController } from './main.controller';

export class MainComponent {

    constructor() { 
        this.controller = MainController;
        this.templateUrl = 'app/main/main.html';
        this.$canActivate = (Auth) => {
            'ngInject';

            return Auth.redirectUnauthenticated();
        };
    }
}

, :

export class AuthService {

    constructor($auth, UserApi, $q, $rootRouter, Storage) {
        'ngInject';

        this.$auth = $auth;
        this.$q = $q;
        this.$rootRouter = $rootRouter;
        this.storage = Storage;
        this.userApi = UserApi.resource;
    }

    /**
     * Check user status
     */
    isAuthenticated() {
        return this.$auth.isAuthenticated();
    }

    /**
     * Redirect user to login page if he is not authenticated
     */
    redirectUnauthenticated() {
        if (!this.$auth.isAuthenticated()) {
            this.$rootRouter.navigate(['Login']);

            return false;
        }

        return true;
    }
}

. $auth satellizer.

, ( ), , $canActivate. , , :)

0

All Articles