路径保护:如何将Observable <response>转换为Observable <boolean>

时间:2017-11-10 12:03:39

标签: angular rxjs observable angular-route-guards

如何转换Observable&lt; Response&gt;进入Observable&lt; boolean&gt;。这是一名路线卫士。

代码:

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

3 个答案:

答案 0 :(得分:1)

您可以创建另一个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
});

答案 1 :(得分: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});

}

步骤3:

let obs=this.Test();
 obs.subscribe(x=>{console.log(x)});

答案 2 :(得分: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;
}