Array not updated when changes occur Angular 10

只愿长相守 提交于 2021-01-05 09:11:41

问题


There is an Observable that sends an array of offers to my component. But when the list is changes (one is deleted) it does not change the list that I get in the component.

I've tried it with ngOnChanges to subscribe to the list again and update the list in my component, but it doesn't detect any changes on the list.

When I use ngDoCheck it worked, but I want a little less drastic solution for this..

offer.service.ts:

    // observable of offers list
      public getAll(): Observable<Offer[]> {
        return of(this.offers);
      }

component.ts:

    offers: Offer[] = [];
      selectedOfferId = -1;
    
      constructor(private offerService: OfferService) { }
    
      ngOnInit(): void {
        this.offerService.getAll().subscribe(data => {
          this.offers = data;
        });
      }
    
      ngOnChanges(): void {
        this.offerService.getAll().subscribe(data => {
          this.offers = data;
        });
      }

回答1:


You can communicate between components using an Observable and a Subject (which is a type of observable), I won't go too much into the details, you can fin more info here, there are two methods: Observable.subscribe() and Subject.next().

Observable.subscribe()

The observable subscribe method is used by angular components to subscribe to messages that are sent to an observable.

Subject.next()

The subject next method is used to send messages to an observable which are then sent to all angular components that are subscribers of that observable.

A workaround solution:

offer.service.ts:

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class OfferService {
    private subject = new Subject<any>();
    
    //...

    getOffers(message: string) {
        return this.subject.asObservable();
    }

    removeOffers() {
      //...remove logic
      this.subject.next({this.offers})
    }

}

component.ts:

 subscription: Subscription;

 ngOnInit(): void {
       this.subscription =  this.offerService.getOffers().subscribe(offers => {
          //...
       })
 }


来源:https://stackoverflow.com/questions/64728809/array-not-updated-when-changes-occur-angular-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!