-2

I have a problem,

I have that :

  getComposition(){
return this.http.get("/api/setup/composition/getComposition",{responseType: 'text'});
}

    var composition;
this.getComposition().subscribe(data => {composition = data});

console.log(composition);

And hen i display composition it return me undefined.. How i can get the result of my request in my var composition ? ...

I have already search a solution... I'm Using Angular

Thanks for your help.

Mathieu d.o
  • 111
  • 6
  • you need to put console.log insider subscribe, the subscription will happen after the console.log as its a side effect – rijin Dec 21 '18 at 15:27
  • The last line of that function is executed *before* anything in the callback. – jonrsharpe Dec 21 '18 at 15:28
  • 1
    Possible duplicate of [How to return value from function which has Observable subscription inside?](https://stackoverflow.com/questions/38291783/how-to-return-value-from-function-which-has-observable-subscription-inside) – jonrsharpe Dec 21 '18 at 15:29
  • Ok ! I understand.. But is it possible to intiialize the variable composition at initialization of my component? To use this variable in the rest of my code ? – Mathieu d.o Dec 21 '18 at 15:54

1 Answers1

2

The subscribe probably never got called, I'm just putting it inside ngOnInit() but you can fit it in any other function:

var composition;

ngOnInit(){

this.getComposition().subscribe(data => {
    this.composition = data
    console.log(this.composition);
  });
}
Aragorn
  • 5,021
  • 5
  • 26
  • 37
  • Ok thanks ! But is it possible to intiialize the variable composition at initialization of my component? To use this variable in the rest of my code ? – Mathieu d.o Dec 21 '18 at 16:23
  • That is exactly what `ngOnInit()` does, initializes the variable (or anything in it) at the initialization of your component. – Aragorn Dec 21 '18 at 16:25