1

How can I transform an Observable<Response> into Observable<boolean>. This is inside a route guard.

Code:

canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean> {

    let obs = this.http
        .get(environment.apiUrl + '/admin', { withCredentials: true})
        .map<Response, boolean>((res: Response) => { return true; });
    return obs;
}

Doesn't work. I don't understand the error message:

The 'this' context of type 'Observable<Response>' is not assignable to method's 'this' of type 'Observable<Response>'.
  Type 'Response' is not assignable to type 'Response'. Two different types with this name exist, but they are unrelated.
    Property 'body' is missing in type 'Response'.

Edit

After wasting 1 hour trying to comprehend the error message I instead used this. Seems to work:

canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean> {
    debugger;
    let subject = new Subject<boolean>();

    let authenticated = this.http.get(environment.apiUrl + '/admin/access', { withCredentials: true})

    authenticated.subscribe((res) => {
        if (res.status == 200)
            subject.next(true);
        else
            subject.next(false);
    }, () => {
        subject.next(false)
    }, () => {
        subject.complete();
    });
    return subject;
}
gyozo kudor
  • 6,284
  • 10
  • 53
  • 80

3 Answers3

2

You can create another observable, which returns the desired data. For ex.:

testFunction(): Observable<Boolean> {
  return Observable.create(observer => {
    this.http
    .get('http://example.com', { withCredentials: true})
    .map((res:Response) => { observer.next(res.status == 200); });
  });
}

And you'll get the result like this:

testFunction().subscribe(result => {
  // here is the result
});
Attila Szász
  • 707
  • 4
  • 22
1

Try this:

Step1:

import { Http, Response } from "@angular/http";

Step2:

Test(): Observable<boolean> {
    let url: string = `http://localhost/WebService/v1/ping`;
    return this.http.get(url).map((res: Response)=>{return res.status==200});

}

Step3:

let obs=this.Test();
 obs.subscribe(x=>{console.log(x)});
sanjay kumar
  • 838
  • 6
  • 10
1

I managed to get it to work using something like this:

canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean> {
    debugger;
    let subject = new Subject<boolean>();

    let authenticated = this.http.get(environment.apiUrl + '/admin/access', { withCredentials: true})

    authenticated.subscribe((res) => {
        if (res.status == 200)
            subject.next(true);
        else
            subject.next(false);
    }, () => {
        subject.next(false)
    }, () => {
        subject.complete();
    });
    return subject;
}
gyozo kudor
  • 6,284
  • 10
  • 53
  • 80