6

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?

gandarez
  • 2,609
  • 4
  • 34
  • 47
Yohsuke Inoda
  • 521
  • 1
  • 6
  • 20

2 Answers2

6

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));
  }
}
Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

If multiple routes subscribe to the same observable, it will call the backend multiple times. Need to add publishReplay : httpClient.get('url').pipe(publishReplay(1),refCount());

KRISHNA R
  • 41
  • 2