I am getting the JSON Object value in my Data service, but All components are loading before my Data service loads. So, I am getting undefined values when I call service method from components.
5 Answers
I supposed you are using a Router to access to your page, so you can simply use the "resolver" feature : RouterLink description.
path: 'app', component: AppPage, resolve: { myData : DataResolve }
Here we ask to resolve the variable "myData" thanks to the resolver DataResolve. DataResolve is a simple Injectable implementing Resolve interface :
import { Resolve } from '@angular/router';
import { Injectable } from '@angular/core';
@Injectable()
export class UserResolve implements Resolve<any> {
constructor(private myService: MyService) {}
async resolve() {
const myData= await this.myService.getMyData().toPromise();
return myData;
}
}
Then when the value are resolve the component will load. And you can get your data from the ActivatedRoute :
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute {
this.route.data.subscribe(() => {
this.data = this.route.snapshot.data.myData;
});
}
Comments
You can use a resolver in your data service:
- In your route you can add
resolveproperty. - Implement the resolve interface in your service and add a resolve method.
- just subscribe to the observable service in your component.
Comments
You can use resolve in router.
Go through link below
Comments
if you using HttpClient for fetching data you need subscribe to stream, because it returns observable
this.MyService.method().subscribe(value => {
// you can use value here
});
or you can use async pipe in template
// controller
value$ = this.MyService.method()
// template
<p>{{value$ | async}}</p>
beside that you can register your service factory into angular providers via APP_INITIALIZER token and your function will be executed when an application is initialized.
@NgModule({
...
providers: [
{ provide: APP_INITIALIZER, useFactory: initSomething, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule {}
2 Comments
Maybe a simpler approach to load your service before any other component is to add it as an argument of the AppComponent of your Angular app
export class AppComponent {
constructor(private myService: MyService) {}
...
}
If you want to do any call at the construction of the service, it is the role of its constructor