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;
});
}
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 => {
//...
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.