简体   繁体   English

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

[英]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. 我是Angular2和Observable的新手,我想检查一下Observable<string[]>类型的Observable getRoles是否包含一个字符串。

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

Observables are asynchronous so you can't use let getRoles = ...map(...) . Observable是异步的,所以你不能使用let getRoles = ...map(...) The map() method is not executed on an array but on an Observable which is always asynchronous. map()方法不是在数组上执行,而是在一个始终异步的Observable上执行。

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). 当源完成时(当我们迭代所有角色时)没有找到匹配元素时,operator first()会发出错误。

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. 这会将所有内容转换为纯truefalse值。 See doc for first() operator what are these argument. 请参阅doc for first()运算符这些参数是什么。 Then I used map() to force convert everything into boolean. 然后我使用map()强制将所有内容转换为布尔值。

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 查看实时简化演示: http//plnkr.co/edit/MtYfGLgqgHACPswFTVJ5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM