How to check if a RxJS Observable contains a string in Angular2?

 ̄綄美尐妖づ 提交于 2019-12-10 15:34:13

问题


I am new to Angular2 and Observable, I want to check if a Observable getRoles which is of type Observable<string[]> contains a string.

public hasRole(name: string): boolean {
    // getRoles is of type Observable<string[]>
    let getRoles = this.tokenService.getTokenInformation().map(element => element.roles);

    if (/* check if name is inside of getRoles */) {
        return true;
    }
    return false;
}

回答1:


Observables are asynchronous so you can't use let getRoles = ...map(...). The map() method is not executed on an array but on an Observable which is always asynchronous.

So proper way to do it could be (I didn't test this code):

public hasRole(name: string): Observable {
    return this.tokenService.getTokenInformation()
        .map(element => element.roles)
        .first(roles => roles.indexOf(name) !== -1);
}

Operator first() emits an error when no matching element was found when the source completed (when we iterated all roles).

Then use this method like:

hasRole('my-role').subscribe(
    role => console.log("has role"),
    error => console.log("doesn't have role"),
)

Edit:

This converts everything to only true or false values. See doc for first() operator what are these argument. Then I used map() to force convert everything into boolean.

public hasRole(name: string): Observable {
    return this.tokenService.getTokenInformation()
        .map(element => element.roles)
        .first(roles => roles.indexOf(name) !== -1, undefined, false)
        .map(val => !!val);
}

See live simplified demo: http://plnkr.co/edit/MtYfGLgqgHACPswFTVJ5



来源:https://stackoverflow.com/questions/40219593/how-to-check-if-a-rxjs-observable-contains-a-string-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!