Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement AuthGuard waiting a connection in Angular 2

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?

like image 906
Yohsuke Inoda Avatar asked Jun 30 '16 10:06

Yohsuke Inoda


People also ask

How does AuthGuard work in Angular?

AuthGuard is used to protect the routes from unauthorized access in angular. How AuthGuard Works? Auth guard provide lifecycle event called canActivate. The canActivate is like a constructor.

Can active guard in Angular?

The canActivate guard checks if the user can visit the specific route or we have to prevent access to that specific route. We use the this guard when we have to check some condition and based on that users have the access to reach that specific route or not, before activating the component or showing it to the user.


1 Answers

Just use map() instead of subscribe(). The router does the subscription by itself to initiate the request.

Don't forget to import map Angular 2 HTTP GET with TypeScript error http.get(...).map is not a function in [null]

I think this should do what you want:

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));
  }
}
like image 52
Günter Zöchbauer Avatar answered Nov 15 '22 04:11

Günter Zöchbauer