2017-08-29 70 views
1
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")}) 

    } 
} 

如何從訂閱返回布爾值。是否有任何解決方法來實現這一目標?如何從anuglar中的訂閱返回布爾值2

這是使服務器的呼叫

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

這個問題更關係到rxjs然後打字稿或角的方法。

正確rxjs方式實現這一目標是從hasPrivilege(..)方法返回一個觀察的,是這樣的:

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() 
    } 
} 

然後訂閱返回可觀察,如:

this.hasPrivilege(..)。subscribe(boolValue => {/ *用布爾值* /}做任何事情)

+0

無法讀取未定義的屬性'subscribe'。錯誤而subscibing this.hasPrivilege(..)。認購(boolValue => { – user630209

+0

你在哪裏調用該方法又如何呢?也許嘗試無「本」關鍵字... – Jonathan

+0

否則它只是這樣一來,從返回「如果「它工作正常,從」其他「它會給出錯誤。 – user630209