Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 362
Devid Avatar asked Oct 18 '22 23:10

Devid


1 Answers

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

like image 195
martin Avatar answered Oct 21 '22 06:10

martin