为什么没有'这种可观察的反应?

时间:2016-11-16 21:08:49

标签: angular rxjs reactive-programming observable

可观察this.currentNodeFilters$ngOnChanged中定义,因为它使用Input()this.node从父组件使用ChangeDetectionStrategy.OnPush(不可变对象)推送。

this.currentNodeFilters$queryParams中的当前combineLatest一起使用。 我期待this.currentNodeFilters$queryParams的任何变化,可观察的this.currentFilters$做出反应。但没有任何反应。

问题:为什么不对变化作出反应?

这是我的代码:

import {Component, OnInit, ChangeDetectionStrategy, Input} from '@angular/core';
import {ActivatedRoute} from "@angular/router";
import {Observable} from "rxjs";

@Component({
  selector: 'filter-content',
  templateUrl: './filter-content.component.html',
  styleUrls: ['./filter-content.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class FilterContentComponent implements OnInit {

  public currentNodeFilters$: Observable<any>;
  public currentFilters:any;

  @Input() node;

  constructor(private route: ActivatedRoute) { }

  ngOnChanges() {
    this.currentNodeFilters$ = Observable.of({
        "params": {
          "nodes": this.node.id
        },
        "order": "asc"
      }
    )
  }

  ngOnInit() {
    const queryParams$ = this.route.queryParams;

    // On regarde les queryParams pour construire currentFilters
    Observable.combineLatest(this.currentNodeFilters$, queryParams$, (currentFilter, queryParams) => {
        const p = Object.keys(queryParams).map(key => {
          const params = {};
          params[key] = queryParams[key];
          return Object.assign({}, {"params": params})
        })

        return Object.assign({}, currentFilter, p);
      })
      .subscribe(currentFilters => this.currentFilters = currentFilters)

   }
}

订阅hml文件

node: {{node | json}} from filter-content<br>
currentNodeFilters$: {{currentNodeFilters$ | async | json}}<br>
currentFilters: {{currentFilters | json}}

1 个答案:

答案 0 :(得分:1)

我看到的主要问题是你在每个ngOnChanges上重新定义currentNodeFilters $ observable。相反,每当你调用ngOnChanges方法时,你应该通过observable推送一个新值。相反,如果你想做这样的事情,你应该使用一个主题。你的代码看起来像这样:

// Create a subject instead of an observable
public currentNodeFilters$: Subject<any> = new Subject();
public currentFilters:any;

@Input() node;

constructor(private route: ActivatedRoute) { }

ngOnChanges() {
    // next the value through the subject
    this.currentNodeFilters$.next{
        "params": {
          "nodes": this.node.id
        },
        "order": "asc"
      }
    )
  }