I have two components: NewItemComponent and ListComponent. When I create new item inside corresponding component I notify ListComponent so it can refresh it's data model:
export class NewItemComponent implements OnInit {
constructor(private itemService: ItemService, private notificationService: NotificationService) {
}
ngOnInit() {
}
createNewItem(item: Item) {
this.itemService.persist(item).subscribe((response: Item) => {
console.log(response);
this.notificationService.notifyNewItemHasBeenCreated(response);
});
}
}
export class ListComponent implements OnInit {
items: Item[];
constructor(private listService: ListService, private notificationService: NotificationService) {
}
ngOnInit() {
this.loadItems();
this.notificationService.item$.subscribe((item) => {
if (item != null) {
this.loadItems();
}
})
}
loadItems(){
this.istService.getItems().subscribe((data: Item[]) => {
this.items= data;
console.log(this.items);
});
}
}
@Injectable({
providedIn: 'root'
})
export class NotificationService {
private _item: BehaviorSubject<Item> = new BehaviorSubject<Item>(null);
public item$ = this._item.asObservable();
constructor() {
}
notifyNewItemHasBeenCreated(item: Item) {
this._item.next(item);
}
}
What makes me worried is that loadItems() calls subscribe() multiple times. Is this ok or there is better way to refetch items based on notification?
loadItems(){
this.listService.getItems().subscribe((data: Item[]) => {
this.items= data;
console.log(this.items);
});
}
ListService returns Observable:
export class ListService {
basePath = 'my-api.com';
apiPath = "item";
constructor(private httpClient: HttpClient) {
}
getItems(): Observable<Item[]> {
return this.httpClient.get<Item[]>(this.basePath + '/' + this.apiPath);
}
}
Thanks in advance and any help will be really appreciated.