In My Angular Application
I made several attempts to get the values using a BehaviorSubject to know when the value was changed or received. I can not get the values before loading the component.
Through this link you can see what you are returning:
https://dev.moip.com.br/v1.5/reference#listar-planos
data.service.ts:
dataOnChanged: BehaviorSubject<any> = new BehaviorSubject({});
getData() {
return new Promise((resolve, reject) => {
this.http.get(this.api_URL + 'plans/, this.httpOptions).subscribe((data: any) => {
// the result is
// data = {plans: Array(5)}
this.dataOnChanged.next(data);
resolve(data);
},
(response: any) => {
reject(response.error);
});
});
}
resolve.service.ts:
constructor(
private dataService: DataService, {
}
* Resolve
* @param {ActivatedRouteSnapshot} route
* @param {RouterStateSnapshot} state
* @returns {Observable<any> | Promise<any> | any}
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any {
return new Promise((resolve, reject) => {
Promise.all([
this.dataService.getData()
]).then(
() => {
resolve();
},
reject
);
});
}
routes.module.ts:
{
path: 'home',
component: HomeComponent,
resolve: {
data: ResolveService,
},
},
home.component.ts:
constructor(
public data: DataService,
) {
this.dataService.dataOnChanged.subscribe((result: any) => {
// no result
debugger;
});
The problem is that I can not load the data returned by HTTP GET before loading the component. I need to load the data before and show the screen.
I think the best way to get the value will be to get it from the ActivatedRoute
In your component, if you inject the ActivatedRoute:
That way, you don't need the BehaviourSubject.
Here is an example on StackBlitz.
When you visit the /about route, it will get a value on a 2second delay to demonstrate
Usage of
BehaviorSubject
is redundant over here instead you can access the resolved data using thedata
property of ActivatedRoute’s snapshot object or subscribe to ActivatedRoutedata
Property which holds the static and resolved data of the current routeit's recommended to use Observables over promises. By converting to a promise you will lose the ability to cancel a request and the ability to chain RxJS operators.
From Docs
data.service.ts:
resolve.service.ts:
routes.module.ts:
home.component.ts:,
or
STACKBLITZ DEMO