Reputation: 364
the main app.component is requesting data from a web service
then it sets a variable in a service called coreService which gets injected everywhere to access these data
the problem is that the others component get loaded before app.component gets the infos, so I get tons of undefined issues
I dont fetch data from coreService otherwise the webservice is called multiple times (tried to use a condition and pipe() but it does not work)
I tried using AfterViewInit, yet it works intermitently
app.component:
ngOnInit() {
this.catalogService.getCampaign().then((data: any) =>
{
this.coreService.campaign=data;
});
}
products.component: (the component loaded in the router-outlet)
constructor(private coreService:CoreService)
{}
ngAfterViewInit()
{
Promise.resolve(null).then(() => { // to avoid value changed error b@#!t from angular
if(this.coreService.campaign)
{
... // we should be here
}
else
{
console.dir(this.coreService);
throw "campaign not loaded yet";
}
});
}
I want the two components to be synced, I mean, the products component has to wait for the coreService to have its data
this undefined in chained then:
@Injectable({
providedIn: 'root'
})
export class AppResolver implements Resolve<boolean> {
constructor(private catalogService: CatalogService, private coreService:CoreService) { }
public resolve(route: ActivatedRouteSnapshot): Promise<boolean>
{
return this.catalogService.getCampaign(CoreService.CAMPAIGN_IDENTIFIER,null).then((data: any) =>
{
this.coreService.campaign=data;
return true;
})
.then(function(result) : Promise<boolean>
{
// below this is undefined and throws an error
//////////////////////////////////////////////
return this.catalogService.getCampaign(CoreService.CAMPAIGN_IDENTIFIER,null).then((data: any) => {
this.coreService.campaign=data;
return true;
});
});
}
}
Upvotes: 0
Views: 128
Reputation: 4874
yo should fetch data in a Resolver.
@Injectable({
providedIn: 'root'
})
export class MyDataResolverService implements Resolve<boolean> {
constructor(private catalogService: CatalogService, private coreService:CoreService) { }
public resolve(): Promise<boolean> {
return this.catalogService.getCampaign().then((data: any) => {
this.coreService.campaign=data;
return true;
});
}
}
then use the resolver in your route configuration
...
{
path: '',
component: AppComponent,
resolve: {
dataResolved: MyDataResolverService
}
}
....
Upvotes: 1