I'm creating a web application using Angular 2 (RC.3) with @angular/router alpha.8. This new router provides "Guard", it helps our to implement to handle authorization redirect.
An official documents are wrote how to create and use Guard, but its sample code does not take account of connecting time. https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard
So I want to use Observable
(or Promise
) in it.
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);
}
);
}
}
But in the above code, canActivate()
function returns Subscription
instance because Observable.prototype.subscribe()
returns Subscription
.
What should I do?