0

I have a component SurveyComponent and a service SurveyService. The SurveyService loads some data form JSON.

I add the SurveyService into the constructor from SurveyComponent.

constructor(public surveyService: SurveyService) {}

In the constructor from SurveyService I load some data.

constructor(private storageService: StorageService) {

    this.finishedSurveys = [];

    this.loadCurrentSurvey();

    this.loadFinishedSurveys();

 }

I put also the SurveyService into the app.module:

.....providers: [SurveyService].....

But the component loads before service so I haven no data in my component. Why does it happen? Can I solve this issue?

Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
Akif
  • 31
  • 3
  • 3
    Possible duplicate of [Angular2: How to load data before rendering the component?](https://stackoverflow.com/questions/35655361/angular2-how-to-load-data-before-rendering-the-component) –  Apr 03 '19 at 11:40
  • That would be happening because you requests in service's constructor may be asynchronous. If you want to wait for data to be loaded before your component loads then use resolvers instead – Ashish Ranjan Apr 03 '19 at 11:40
  • Service actually does load before the component, it's just that your data is not there yet. – Roberto Zvjerković Apr 03 '19 at 11:46

2 Answers2

0

you can use resolve for the angular router. E.g. Make a class APIResolver like

import { Injectable } from '@angular/core';
import { APIService } from './api.service';

import { Resolve } from '@angular/router';

import { ActivatedRouteSnapshot } from '@angular/router';

@Injectable()
export class APIResolver implements Resolve<any> {
 constructor(private apiService: APIService) {}

 resolve(route: ActivatedRouteSnapshot) {
   return this.apiService.getItems(route.params.date);
 }
}

Then, resolve your corresponding router like

{
 path: 'items',
 component: ItemsComponent,
 resolve: { items: APIResolver }
}
-1

You can refer to this link to use OnInit

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnInit {
  ngOnInit() {
    you call the service that you want to execute 
  }
}
H Mirindra
  • 94
  • 4