2016-06-30 9 views
6

Tworzę aplikację internetową za pomocą Angular 2 (RC.3) z @ kątowym/routerem alpha.8. Ten nowy router zapewnia funkcję "Guard", pomaga nam implementować w celu obsługi przekierowania autoryzacji.Jak zaimplementować AuthGuard czekając na połączenie w Angular 2

Oficjalne dokumenty są pisane, jak tworzyć i używać Guard, ale ich przykładowy kod nie uwzględnia czasu połączenia. https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard

Więc chcę użyć w tym celu Observable (lub Promise).

export class ApiService { 
    constructor(private _http: Http) {} 
    head(url: string): Observable<any> { 
    const req: any = { method: RequestMethod.Head, url: URI_SCHEME + url }; 

    return this._http.request(new Request(req)); 
    } 
} 

export class AuthGuard implements CanActivate { 
    constructor(private _api: ApiService) {} 

    canActivate(): Observable<boolean> { 
    return this._api.head('/users/self').subscribe(
    (): Observable<boolean> => { 
     // when gets 200 response status... 
     return Observable.of(true); 
     }, 
    (): Observable<boolean> => { 
     // when gets 401 error response... 
     // TODO: redirect to sign-in page. 
     return Observable.of(false); 
     } 
    ); 
    } 
} 

Ale w powyższym kodzie canActivate() zwraca Subscription przykład dlatego Observable.prototype.subscribe() powraca Subscription.

Co należy zrobić?

Odpowiedz

6

Po prostu użyj map() zamiast subscribe(). Router sam wykonuje subskrypcję, aby zainicjować żądanie.

Nie zapomnij importować mapAngular 2 HTTP GET with TypeScript error http.get(...).map is not a function in [null]

myślę, że powinni robić to, co chcesz:

export class AuthGuard implements CanActivate { 
    constructor(private _api: ApiService) {} 

    canActivate(): Observable<boolean> { 
    return this._api.head('/users/self') 
    .map(response => { 
     this.doSomethingWithResponse(response.json())); 
     return true; 
    }) 
    .catch(err => Observable.of(false)); 
    } 
} 
+0

wow! Dziękuję bardzo. –