2016-09-15 69 views
0

我正在使用angular2 rc6,並不介意使用最新公佈的版本。 我正在嘗試實現路由器插座,以提供只有經過身份驗證的用戶的訪問權限。Angular2:在新版本rc6中將RouterOutlet擴展爲激活方法

我有這個代碼塊在以前的版本中工作。

舊代碼:

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); 
 
    //} 
 
}

+0

你能張貼工作代碼?答案似乎是代碼,而不是你的代碼。 –

+0

接受的答案使用路徑的「canActivate」屬性,它執行查詢者想要解決的工作。但是,如果出於其他原因使用「激活」方法存在解決方案,我很感興趣。 –

回答

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; 
} 

而且我的login服務是:

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!'); 
    } 
} 

希望,這可以幫助你......

相關問題