1

如何将 Observable<Response> 转换为 Observable<boolean>。这是在路线守卫内。

代码:

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;
}

不工作。我不明白错误信息:

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'.

编辑

在浪费了 1 小时试图理解错误消息后,我改用了这个。似乎工作:

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;
}
4

3 回答 3

2

您可以创建另一个 observable,它返回所需的数据。例如:

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

你会得到这样的结果:

testFunction().subscribe(result => {
  // here is the result
});
于 2017-11-10T12:13:11.633 回答
1

我设法让它使用这样的东西工作:

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;
}
于 2017-11-10T13:16:43.780 回答
1

尝试这个:

步骤1:

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

第2步:

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

}

第三步:

let obs=this.Test();
 obs.subscribe(x=>{console.log(x)});
于 2017-11-10T12:37:32.953 回答