1

I have some troubles with setting value to my variable in ngOnInit() function. I have tried to seeing variable in console after setting but I received only "undefined". How to make it work?

export class GalleryComponent implements OnInit  { 

actualModelType: modelInterface[];
femaleModels: modelInterface[];

constructor(private _femaleModelsService: FemaleModelsService) {
    this.actualModel = null;
    this.clicked = false;
}

ngOnInit() {
    this._femaleModelsService.getFemaleModels()
        .subscribe( responseFemaleModelsData => this.femaleModels = responseFemaleModelsData );


    this.actualModelType = this.femaleModels;
    console.log( this.actualModelType, this.femaleModels );
}
}
Kamczatka
  • 151
  • 1
  • 2
  • 15
  • Subscriptions are *asynchronous*, that's the whole point of them. You get access to the data *inside the callback*. – jonrsharpe Jun 13 '17 at 20:54
  • Possible duplicate of [Angular 2 - Return data directly from an Observable](https://stackoverflow.com/questions/37867020/angular-2-return-data-directly-from-an-observable) – jonrsharpe Jun 13 '17 at 20:54

1 Answers1

2

The problem you have here is that you are calling for data from FemaleModelsService but you are also assigning values you don't have yet.

Observables and promises are asynchronous, so you have to wait for their response in order to manipulate what they are returning to you. As explained by jonrsharpe, you have to get the data inside the callback in order to do what you are looking for.

Try this :

ngOnInit() {
    this._femaleModelsService.getFemaleModels().subscribe(
        responseFemaleModelsData => {
            this.femaleModels = responseFemaleModelsData;
            this.actualModelType = this.femaleModels;
            console.log(this.actualModelType, this.femaleModels);
        }
    );
}
nvkfr
  • 140
  • 1
  • 9
  • I edited the code, try it please. If it still doesn't work, i'll need more detail on your code (you service code and the data you are calling) – nvkfr Jun 15 '17 at 12:55