首页 > 解决方案 > 如何在 Angular 的 Observable 中使用 Arrays.some?

问题描述

我有调用服务器并检索 id 列表的服务。我想使用某种方法来查找用户的当前 ID 是否等于其中一个 ID。

我试过了:

 private isCurrentUserExistsInUserIdsList(): boolean {
        return this.userService.findIds().pipe(
            map((userIds: number[]) => {
                userIds.some(id => {
                    return id == this.currentUserId;
                });
            })
        );
    }

我被困在这里,我怎样才能得到某种方法的结果?

标签: angularbooleanobservable

解决方案


我喜欢在同一个服务中关联所有的 observables。这样你就可以

//in your userService:
public isCurrentUserExistsInUserIdsList(currentId:number): Observable<boolean>
{
     return this.findIds().pipe(
       map((res:any[])=>res.some(x=>x==currentId)))
}

//or, if you use the in the "map" "{" "}" you need use return
public isCurrentUserExistsInUserIdsList(currentId:number): Observable<boolean>
{
     return this.findIds().pipe(
       map((res:any[])=>{
        return res.some(x=>x==currentId)
      }))
}

所以,你可以订阅你的组件

this.isCurrentExistInUserIdsList(this.currentUserId).subscribe(res=>{
     console.log(res)
})

推荐阅读