Thanks for the link provided, I think I understood the differences and how you solved the problem, I found it strange that in the tutorial they don’t approach it that way. I even wonder if this problem is intentional, by some incomplete way of the tutorial, or if was my fault beacause some mistake I made. I ended up using the lifecycle hook as a last measure, I know that Angular alone manages change detection, but even that didn’t work. I tried to make some changes using your method but it also didn’t work:
hero.service.ts
public heroes = new BehaviorSubject<Hero[] | null>(null);
getHeroes(): Observable<Hero[]>{
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
tap(res=>{
this.log('fetched heroes');
this.heroes.next(res);
}),
catchError(this.handleError<Hero[]>('getHeroes', []))
);
}
watchHeroes(): Observable<Hero[]> { return this.heroes; }
updateHero(hero:Hero):Observable<any>{
return this.http.put(this.heroesUrl, hero, this.httpOptions).pipe(
tap(res =>{
this.log(`updated hero id=${hero.id}`)
this.getHeroes();
}),
catchError(this.handleError<any>('updateHero'))
);
}
hero-detail.component.ts
hero:Hero;
constructor(
private route: ActivatedRoute,
private heroService: HeroService,
private location: Location
) { }
ngOnInit() {
this.getHero();
}
getHero(): void{
const id = +this.route.snapshot.paramMap.get('id');
this.heroService.getHero(id).subscribe(hero => this.hero = hero);
}
goBack(): void{
this.location.back();
}
save(): void{
this.heroService.updateHero(this.hero)
.subscribe(() => this.goBack());
}
dashboard.component.ts
heroes$:Observable<Hero[]> = new Observable<Hero[]>();
heroes:Hero[] = [];
ngOnInit() {
this.getHeroes();
this.heroes$.subscribe(res => {
return this.heroes = res;
});
}
getHeroes():void{
this.heroService.getHeroes().subscribe(_ =>this.heroes$ = this.heroService.watchHeroes());
}
Note: @Tommertom, I don’t know if I understand your question, but I’m using ionic 5 and I adapted the tutorial solution for the app.