Hello there dear coders, I have a project that i have to save some products as favorites in favorite component section, I must save them to a service then call it from that specific component, anyone can help how to do that in real time and asynchronously ? any guide or clue would be enough and appreciated.
Asked
Active
Viewed 85 times
1
-
1Be specific while asking question. This question already has an answer @https://stackoverflow.com/questions/50371582/angular-6-passing-messages-via-service-to-from-component-to-message-component – Yogesh Sanchihar Jun 13 '19 at 12:00
-
this answer that you have mentioned is similar to what i asked but in specific i want to get some data information and show it inside another component in the same time just like shopping cart in e-commerce websites – ArmondHIM Jun 13 '19 at 12:09
1 Answers
1
For this I would consider using a BehaviorSubject
in your service. Something like this would allow you to update the Subject via the component and see it update on the UI in real time.
This is how I have set up a simple working example:
favorite.service.ts
import { BehaviorSubject } from 'rxjs';
export class FavoriteService {
public favs = new BehaviorSubject([]);
constructor() { }
public updateSubject(newItem: any[]): void {
this.favs.next(newItem)
}
}
favorite.component.ts
export class FavoriteComponent implements OnInit {
public favorites = this.service.favs;
ngOnInit(): void {
const items = ['item1', 'item2'];
this.service.updateSubject(items);
}
}
The you can see the updated array in your html as follows:
favorite.component.html
<div *ngFor="let item of favorites.value">
{{item}}
</div>
So whenever you call the updateSubject method it will update the behaviour subject with a new array and any items added/changed should appear on you html straight away.

max
- 134
- 1
- 3