user7082181
user7082181

Reputation: 364

Angular 2 - waiting for a service to have the infos - return promise when variable is set

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

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

Answers (1)

ysf
ysf

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

Related Questions