0

I am using angular 5 and I have installed the httpClient Module so I can get data from an api.

On my app.component.ts I have this:

getData() {
    this.http.get('url to get xml data from', { responseType: 'text' }).subscribe(data => {
    return data;
 });
}

What I need to do it to call this method from my ngOnInit so that I can use the data outside the method so I tried this:

 ngOnInit() {
    this.result = this.getData();
}

But the above is not giving me the data so what I'm I missing for this to work with Angular?

3 Answers 3

0

Modify your first method to simply return an async result from your API call, then subscribe to the method itself.

getData() {
    return this.http.get('url to get xml data from', { responseType: 'text' });
}

and in you ngOnInit

ngOnInit() {
    this.getData().subscribe(res => {
      this.result = res;
   });
}
Sign up to request clarification or add additional context in comments.

Comments

0
getData() {
    return this.http.get('url to get xml data from', { responseType: 'text' });
}


 ngOnInit() {
this.getData().subscribe(data => {
    this.result = data;
 });
}

Comments

0
     getData() {
   return this.http.get('url to get xml data from', {
     responseType: 'text'
   });
 }
 ngOnInit() {
   this.getData().subscribe(data => {
     this.result = data;
   });
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.