如何检查RxJS Observable在Angular2中是否包含字符串?

问题描述:

我是Angular2和Observable的新手,我想检查类型为Observable<string[]>的Observable getRoles是否包含字符串.

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;
}

可观察对象是异步的,因此您不能使用let getRoles = ...map(...). map() 方法不是在数组上执行,但在总是异步的Observable上执行.

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

操作员 first() 当源完成时(当我们迭代所有角色时)未找到匹配的元素时,将发出错误.

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"),
)

这会将所有内容转换为仅truefalse值.请参阅doc中的first()运算符,这些参数是什么.然后,我使用map()强制将所有内容都转换为布尔值.

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

观看现场简化演示: http://plnkr.co/edit/MtYfGLgqgHACPswFTVJ5