I want to get observable data from the backend Firestore through resolver.guard to the component via ActivatedRoute.
I managed to get the first data, but it is not updating to changes.
When visiting the page, the component can retrieve the data but seems not to listen to any changes afterward.
resolver
export class PostExistGuard implements Resolve<any> {
constructor(
private firestore: Firestore,
private router_service: RouterService,
private profile_service: ProfileService
) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any> | Promise<any> | any {
const post_id = route.paramMap.get('id');
const username = route.paramMap.get('username');
console.log('Preload guard initialized...');
return this.profile_service.profile_user_uid$.pipe(
switchMap((uid) => {
return docData(
doc(this.firestore, 'users', uid, 'posts', post_id!)
).pipe(
switchMap((post) => {
if (post) {
console.log(post);
return of(post);
} else {
this.router_service.routeToMain();
return of(null);
}
})
);
})
);
}
}
component.ts
export class PostComponent implements OnInit {
post$?: Observable<Post | undefined>;
data$?: Observable<{ post: Post; profile: _User; user: _User }>;
user?: _User;
constructor(
public profile_service: ProfileService,
private route: ActivatedRoute,
public user_service: UserService,
public share_buttons_service: ShareButtonsService,
public posts_service: PostsService,
public router_service: RouterService
) {
this.data$ = combineLatest([
// stream 1 - profile post
this.route.data.pipe(
map((data: Data, resolve) => {
console.log(data[0]);
return data[0];
})
) as Observable<Post>,
// stream 2 - profile user,
this.profile_service.profile_user$ as Observable<_User>,
// stream 3 - current user
// assuming that user$ emits at least once, even there is no user
this.user_service.user$ as Observable<_User>,
]).pipe(
// if there is a user, check if they have liked the post
switchMap(([post, profile, user]) =>
user ? this.getLike(post, profile, user) : of({ post, profile, user })
)
);
}