如何在anuglar 2中从subscribe返回布尔值

时间:2017-08-29 10:33:41

标签: typescript rxjs

hasPrivilege(privilege: string): boolean {
    let isPrivilege: PrivilegeModel[] = [];
    let val :  boolean;
    if (this.loginService.privilegeList != null && this.loginService.privilegeList != undefined && this.loginService.privilegeList.getValue() != null) {
        isPrivilege = this.loginService.privilegeList.getValue().filter(item => item.name === privilege);
        return this.isPrivilege(isPrivilege);
    } else {
       let val =  this.getUserRolesAndMenus(privilege);
        console.log("after2" +val);
         this.getUserRolesAndMenus().subscribe(result => {
           let val = result.roles.filter((element: any) => {
                return element.privileges.filter(function (item: any) {
                    return item.name === privilege
                }).length != 0
            }).length != 
            return val; // can't return this.
      },() =>{console.log("completed")})

    }
}

如何从subscribe返回布尔值。有没有解决这个问题的工作?

这是进行服务器调用的方法

getUserRolesAndMenus() : Observable<boolean> {
        let headers = new Headers();

        return this.http.get(ROLES_AND_MENUS + AppUtils.ID, { headers: headers })
            .map(response => response.json())
            .catch(this.handleError)
    }

1 个答案:

答案 0 :(得分:1)

这个问题与rxjs然后是typescript或Angular有关。

实现此目的的正确rxjs方法是从hasPrivilege(..)方法返回一个Observable,如:

hasPrivilege(privilege: string): Observable<boolean> {
let isPrivilege: PrivilegeModel[] = [];
let val :  boolean;
if (this.loginService.privilegeList != null && this.loginService.privilegeList != undefined && this.loginService.privilegeList.getValue() != null) {
    isPrivilege = this.loginService.privilegeList.getValue().filter(item => item.name === privilege);
    return Observable.of(this.isPrivilege(isPrivilege));
} else {
     return this.getUserRolesAndMenus()
  }
}

然后订阅返回的Observable,如:

  

this.hasPrivilege(..)。subscribe(boolValue =&gt; {/ *用布尔值* /}做任何事情)