Angular2:在新版本rc6中扩展RouterOutlet以获取激活方法

时间:2016-09-15 15:23:15

标签: angular angular-ui-router

我正在使用angular2 rc6并且不介意使用最新发布的版本。 我正在尝试实现路由器插座,以仅提供对经过身份验证的用户的访问。

我有这段代码在以前的版本中有效。

旧代码:

import {Directive, Attribute, ElementRef, DynamicComponentLoader} from 'angular2/core';
import {Router, RouterOutlet, ComponentInstruction} from 'angular2/router';

@Directive({
    selector: 'router-outlet'
})

export class AuthCheck extends RouterOutlet {
    publicRoutes: any;
    private parentRouter: Router;
    
    constructor(_elementRef: ElementRef, _loader: DynamicComponentLoader, _parentRouter: Router,
    @Attribute('name')nameAttr:string) {
        super(_elementRef, _loader, _parentRouter, nameAttr);
        
        this.parentRouter = _parentRouter;
        this.publicRoutes = {
            'login': true
        };
    }
    
    activate(instruction: ComponentInstruction) {
        let url = instruction.urlPath;
        
        if(!this.publicRoutes[url] && !localStorage.getItem('auth_key')){
            this.parentRouter.navigateByUrl('/login');
        }
        
        return super.activate(instruction);
    }
}

我正在尝试将代码更改为在rc 6中工作,但需要一些帮助才能实现“激活”方法以提供相同的行为:

更改了代码:

//import {Directive, Attribute, ElementRef, DynamicComponentLoader} from '@angular/core';
import {Router, RouterOutlet, RouterOutletMap, ActivatedRoute, } from '@angular/router';

import {
    Component, Directive, ComponentMetadata, Input, ReflectiveInjector,
    ViewContainerRef, Compiler, NgModule, ComponentRef, ComponentFactoryResolver, Injector, ResolvedReflectiveProvider
} from '@angular/core';

@Directive({
    selector: 'router-outlet'
})

export class AuthCheck extends RouterOutlet {
    publicRoutes: any;
    private parentRouter: RouterOutletMap;

    constructor(_parentOutletMap: RouterOutletMap, _location: ViewContainerRef, _resolver: ComponentFactoryResolver,
            name: string)
    //constructor(_elementRef: ViewContainerRef, _loader: any, _parentRouter: Router,
    //    @Attribute('name') nameAttr: string)
    {
        super(_parentOutletMap, _location, _resolver, name);

        this.parentRouter = _parentOutletMap;
        this.publicRoutes = {
            'login': true
        };
    }

    activate(activatedRoute: ActivatedRoute, loadedResolver: ComponentFactoryResolver, loadedInjector: Injector, providers: ResolvedReflectiveProvider[], outletMap: RouterOutletMap) {
        //implementation

    }

    //activate(instruction: any) {
    //    let url = instruction.urlPath;

    //    if (!this.publicRoutes[url] && !localStorage.getItem('auth_key')) {
    //        this.parentRouter.registerOutlet.('/login');
    //    }

    //    return super.activate(instruction);
    //}
}

1 个答案:

答案 0 :(得分:0)

我在角度2 rc7中使用这种类型的解决方案。希望,这对你也有帮助。

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {

    if (state.url !== '/login' && !this.authService.isLoggedIn()) {
        this.router.navigate(['/login']);
        return false;
    }

    return true;
}

我的LoginService也是:

import { Injectable }     from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Router } from '@angular/router'
import { Observable }     from 'rxjs/Rx';
import { IMenu } from '../interfaces/menu';
import { AppSettings } from '../AppSettings';

@Injectable()
export class LoginService{
    private _baseUrl:string = AppSettings.API_ENDPOINT;
    private _loggedIn = false;

    constructor(private _http : Http, private  _router : Router){
        this._loggedIn = !!localStorage.getItem('auth_token') 
        && !!localStorage.getItem('role')
        && !!localStorage.getItem('menu')
    }


    //Post function to send username and password to authorize in the server
    login(Username:string, Password:string) : Observable<IMenu[]>{
        let headers = new Headers();
        headers.append("Authorization", "Basic " + btoa(Username + ":" + Password)); 
        headers.append("Content-Type", "application/x-www-form-urlencoded");
        return this._http.post(this._baseUrl+"auth/login", " " , {headers: headers}  ).delay(2000).
            map((response: Response) => {
                <IMenu[]>response.json();
                localStorage.setItem("menu",JSON.stringify(<IMenu[]>response.json()));
                localStorage.setItem("auth_token", response.headers.get("Token"));
                localStorage.setItem("role", response.headers.get("Role"));
            }).catch(this.handleError);
    }

    logout() {
        localStorage.removeItem("auth_token");
        localStorage.removeItem("menu");
        localStorage.removeItem("role");
        this._router.navigate(['/login']);
        return false;
    }

    isLoggedIn() {
        return this._loggedIn;
    }

    private handleError(error: Response){
        return Observable.throw(error.json().error || 'Server Error!');
    }
}

希望,这有助于你......