typescript 从 Observable<T> 过滤所有“空”值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43043517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:23:21  来源:igfitidea点击:

Filter all 'null' values from an Observable<T>

javascriptangulartypescriptrxjsobservable

提问by fasth

I have a service with a subject:

我有一个主题的服务:

@Injectable() export class UserService() {
    private currentUserSubject = new BehaviorSubject<User>(null);
    public currentUser = this.currentUserSubject.asObservable().distinctUntilChanged(); 

    ... // emitting new User    
}

Have a component I inject this service into and subscribing on updates:

有一个组件,我将此服务注入并订阅更新:

@Component() export class UserComponent {
    constructor(private userService: UserService) {
        this.userService.currentUser
            .subscribe((user) => {
                // I want to see not null value here
            })
    }
}

I want to apply something to Observable<User>to filter all null values and get into subscribe only when Useris actually loaded.

我想应用一些东西来Observable<User>过滤所有空值并仅在User实际加载时才进入订阅。

回答by snorkpete

Add a filter operator to your observable chain. You can filter nulls explicitly or just check that your user is truthy - you will have to make that call depending on your needs.

将过滤器运算符添加到您的可观察链。您可以显式过滤空值或仅检查您的用户是否真实 - 您必须根据您的需要进行该调用。

Filtering out null users only:

仅过滤掉空用户:

public currentUser = this.currentUserSubject
                         .asObservable()
                         .filter(user => user !== null)
                         .distinctUntilChanged(); 

回答by ackuser

Anoter way to check the value exists

检查值是否存在的另一种方法

public currentUser = this.currentUserSubject
                         .asObservable()
                         .filter(Boolean)
                         .distinctUntilChanged(); 

回答by Amit Portnoy

with rxjs@6and typescript the recommended (readable/maintainable) way is to define the following type guard:

使用rxjs@6和打字稿推荐的(可读/可维护)方式是定义以下类型保护:

export function isNonNull<T>(value: T): value is NonNullable<T> {
  return value != null;
}

and augment a subject with pipeand filter:

并用pipe和扩充主题filter

subject.pipe(filter(isNonNull))

回答by Wilt

It's as simple as:

这很简单:

filter(user => !!user),

If user evaluates to false, the filter will not be passed.

如果用户评估为 false,则不会通过过滤器。

So would filter these falsy values (link to Falsy on MDN).

所以会过滤这些假值(链接到 MDN 上的 Falsy)