bvdb
bvdb

Reputation: 24770

how to create and update an observable, which depends on an @Input

A simple component has an input (i.e. criteria) and an observable (i.e. result$).

class Foo {
  @Input()
  private criteria: string;

  private result$: Observable<any>;

  constructor(private service: MyService) { }
}

The class MyService, provides a method, which consumes the criteria and returns the observable which should be used to set/update result$.

service.fetchResult(criteria: string): Observable<any>

What is the state-of-the-art way to create the observable, by using this service. The most important requirement being:

Upvotes: 2

Views: 1052

Answers (1)

Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

With set:

_criteria: Criteria; // set local variable if this input needed elswhere
@Input()
set criteria(c: Criteria) {
  this.service.someMethod(c);
  this._criteria = c;
}

With OnChanges:

ngOnChanges(changes: SimpleChanges) {
  let criteria = changes.criteria;
  if(criteria && criteria.currentValue !== criteria.previousValue){
    this.service.someMethod(criteria);
  }
}

Upvotes: 1

Related Questions