To share an Observable for multiple
observers
, you need something like the share
operator.
Example:
import {Observable} from 'rxjs';
import {share} from 'rxjs/operators'
export class dataService{
public data$=Observable<Idata[]>
constructor(http:HttpClient)
{
this.data$=this.http.get<Idata[]>('https://jsonplaceholder.typicode.com/posts').pipe(share());
}
public getPosts():Observable<Idata[]>
{
return this.data$
}}
This operator is a specialization of publish
which creates a
subscription when the number of observers goes from zero to one, then
shares that subscription with all subsequent observers until the
number of observers returns to zero, at which point the subscription
is disposed.
Refer this for more
Since you want to get resolved data before navigating to the new route you could use Resolve
guard
which Performs route data retrieval before route activation.
you can access the resolved data using the data
property of ActivatedRoute’s snapshot object or subscribe to ActivatedRoute data
Property which holds the static and resolved data of the current route
resolve.service.ts:
import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import {Observable} from 'rxjs';
@Injectable()
export class resolver implements Resolve<Observable<any>> {
constructor(private service:Service) {}
resolve() {
return this.dataService.getdata();
}
}
routes.module.ts:
{
path: 'home',
component: HomeComponent,
resolve: {
data: resolver,
},
},
.component.ts:,
constructor( private route:ActivatedRoute) {
this.route.data.subscribe(value=>{
console.log(value);
});}
STACKBLITZ DEMO
Refer
1. fetch-data-before-navigating
- Route Resolvers