Angular 2+ Observable - 检查if语句中的结果

时间:2017-05-12 20:50:08

标签: angular

是否可以在if语句中检查Observable的结果?

类似的东西:

if( this.loginsService.isAuthenticated().subscribe() == true ){
}

我的登录服务:

  isAuthenticated(){
     return this.http.get('login/authenticated')
      .map(res => res.json());
  }  

3 个答案:

答案 0 :(得分:3)

您应该subscribe获取数据

isAuthenticated():boolean{
     return this.http.get('login/authenticated')
      .map(res => res.json()).subscribe(data => return data);
  }  

或者您可以放入本地方法并使用如下

isLoggedIn() :boolean{
   this.loginsService.isAuthenticated().subscribe(data => {
       return data; 
   });
 }

if(this.isLoggedIn() == true ){
}

答案 1 :(得分:0)

它会返回Subscription,它始终为真,因为它是Object

所以这不起作用。做这样的事情。

this.loginsService.isAuthenticated().subscribe( isAuth => {
    if(isAuth) {
        //Take action
    }
})

答案 2 :(得分:0)

简单地返回Observable的结果有点困难,因为Observables实际上不能被视为单个值。

更改方法以返回Observable

isAuthenticated(): Observable<boolean> { // make the method return an Observable
    return this.http.get('login/authenticated')
      .map(res => res.json())
      .map(json => json.isAuthenticated) // get the value from the json, since you want a boolean
      .share(); // this will make it a hot observable. If you subscribe an observable that has not been "shared", it will make the HTTP call for every subscriber. sharing the observable will make it return the same value for that observable.
}

,用法包括订阅observable:

export class AppComponent {
    isAuthenticated: boolean;

    constructor(private loginService: LoginService) {
        // you can save the value by subscribing once
        this.getIsAuthenticated().subscribe((isAuthenticated: boolean) => {
            this.isAuthenticated = isAuthenticated;
        };
    }

    getIsAuthenticated(): Observable<boolean> {
        return this.loginService.isAuthenticated();
    }
}

或在HTML中:

<!-- use the Async pipe to get the value for you -->
<div *ngIf="getIsAuthenticated() | async">Im Authenticated!</div>