如何检查Subject是否不为null?

时间:2019-06-07 17:16:18

标签: angular rxjs angular7

我有以下代码:

@Injectable()
export class FilterRegister {
  public registerFilter: Subject<any> = new Subject();
  public registerFilterParameters: Subject<any> = new Subject();

  getFilter(): Observable<any> {
    return this.registerFilter.asObservable();
  }

  getParameters(): Observable<any> {
    return this.registerFilterParameters.asObservable();
  }
}

如果registerFilter不为null,如何检入模板?喜欢:

<div *ngIf="!!registerFilter"></div>

1 个答案:

答案 0 :(得分:1)

由于可以观察到registerFilter,因此您需要使用async管道或使用subscribe

两个

registerFilter$: Observable<any>

this.registerFilter$ = service.getFilter();

<div *ngIf="(registerFilter$ | async)"></div>  

registerFilter : any;

service.getFilter().Subscribe((value) => this.registerFilter = value);

<div *ngIf="registerFilter"></div>  

建议

请注意,这将是更清洁的服务实现。

export class FilterRegister {
  registerFilter$ : Observable<any> = this.registerFilter.asObservable();
  registerFilterParameters$ : Observable<any> = this.registerFilterParameters.asObservable();
  private registerFilter: Subject<any> = new Subject();
  private registerFilterParameters: Subject<any> = new Subject();

  foo() {
    this.registerFilter.next('value');
  }
}