angular 2过滤器BehaviorSubject

时间:2017-07-06 07:03:12

标签: angular filter angular2-observables array-filter behaviorsubject

我尝试过滤Angular 2中的BehaviorSubject。服务中的佣金对象将通过http请求获取数据。但是因为它的实例是" null"过滤器代码行有错误。

错误:

  

无法阅读财产' 0'为null

.filter((commission: Commission[], index) => commission[index]._id === this.commissionid)

这是代码:

commissionService:

public commissions: Subject<Commission[]> = new BehaviorSubject<Commission[]>(null);

在组件中:

  ngOnInit() {
    this.commissionService.commissions
        .filter((commission: Commission[], index) => commission[index]._id === this.commissionid)
        .subscribe(data => {console.log(data); })
  }

如果我更改this.commissionid,这个过滤器是否可行?谢谢!

2 个答案:

答案 0 :(得分:3)

您希望主题中包含单个对象,因此请使用rxjs first运算符。 http://reactivex.io/documentation/operators/first.html

init_obj(id) {
    this.commissionService.commissions
        .first(c => c._id === id)
        .subscribe(data => {
            this.commission = data;
        })
}

答案 1 :(得分:0)

现在我找到了一个解决方案,谢谢你的帮助,这里有完整的代码:

  ngOnInit() {
    this.route.params.subscribe((params: Params) => {
      this.commissionid = params.commissionid;
      if (this.commissionid) { this.init_obj(this.commissionid); }
    });

  }


  init_obj(id) {
    this.commissionService.commissions
        .map(function(data) {
          if (data) { return data.find(commission => commission._id === id); }
        })
        .subscribe(data => {
          if (data) { this.commission = data; }
        })

  }