Angular2 how to update an item inside an observable collection

前端 未结 2 1405
情歌与酒
情歌与酒 2021-02-07 19:40

Update, in short:

I am looking for the equivalent of doing something like this but for an Observable rather than a regular array:



        
相关标签:
2条回答
  • 2021-02-07 20:10

    I don't think you fully understand how Observables work. What you call here "observable collection" is not what you might think it is, as in "collection of observable elements".

    What it is, actually, is a stream of emitted collections. So when you have Observable<Model[]>, it's not a collection that's being observed by some observer, it's actually a stream of emitted Model[] collections. In that sense, you can't update the emitted value (obviously, as it already has been emitted), but what you want is it for observable to emit another, updated collection of Model.

    Before you try that, you'll have to know that you can't emit something from observable that you haven't created yourself. What you need is a Subject, an object that is both Observable and Observer (it inherits from both Observer and Observable interfaces).

    So, let's construct something like that:

    subject: Subject<Proposal[]> = new Subject();
    _proposals: Proposal[] = [];
    
    get proposals() {
      return this.subject.asObservable();
    }
    

    Let's say you get your proposals from some API call:

    http.get("...").map(response => response.json().subscribe(data => {
      this._proposals= <Proposal[]>data; // save your data
      this.subject.next(this._proposals); // emit your data
    });
    

    And now, you want to update your data:

    updateProposals() {
      this._proposals = this._proposals.filter(...); // or whatever
      this.subject.next(Object.assign({}, this._proposals)); // emit completely new value
    }
    

    This may seem like a lot and I would recommend reading more on how Observables work for the sake of future issues that you might have. Cheers.

    0 讨论(0)
  • 2021-02-07 20:14

    You can do it in below ways

    • use | async pipe
    • create a private variable and in your subscribe block add value to that which will reflect there.
    0 讨论(0)
提交回复
热议问题