I am working on an angular app where I am subscribing data in service and emitting data using Subject in component.html
and in component.ts
I am subscribing to get the latest value.
My problem is when I refresh the page I get data in the console but I don't see it on the template. Also, when I click on the router link again I can see the data after the first click.
service.ts
public_Data= new BehaviorSubject<any>(null);
getDemo2(){
this.http.get<UPost[]>(`https://write-your-heart-out-b338b.firebaseio.com/post/${this.uid}/public.json`)
.pipe(
map(responseData => {
const postsArray: UPost[] = [];
for (const key in responseData) {
if (responseData.hasOwnProperty(key)) {
postsArray.push({ ...responseData[key] });
}
}
return postsArray;
})
)
.subscribe(posts => {
this.public_Data.next(posts)
this.combine()
});
}
component.ts
allpost: UPost[] = [];
constructor( private acrud: ACrudService) { }
ngOnInit(): void {
//this.acrud.getAllData()
this.acrud.getDemo1();
this.acrud.getDemo2()
console.log("oninitnt methid")
this.allSub= this.acrud.public_Data.subscribe(d=>{
console.log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$",d)
})
component.html
<div class="card row" *ngFor="let i of allpost ; let c = index">
<div class="col-md-9 col-xs-9 main-content">
<h2 class="title">{{ i.title }}</h2>
<p>{{ i.description }}</p>
</div>
</div>
Your big issue here is that you're not handling the data reactively. The simplest way to fix your issue is to change your component constructor to the following:
constructor( public acrud: ACrudService) { }
Then change your HTML to the following:
<div class="card row" *ngFor="let i of acrud.public_Data | async; let c = index">
<div class="col-md-9 col-xs-9 main-content">
<h2 class="title">{{ i.title }}</h2>
<p>{{ i.description }}</p>
</div>
</div>