Javascript / Angular httpClient从url获取数据并传递外部方法 [英] Javascript / Angular httpClient get data from url and pass outside method

查看:67
本文介绍了Javascript / Angular httpClient从url获取数据并传递外部方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是角色5,我已经安装了 httpClient 模块,因此我可以从api获取数据。

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

在我的app.component.ts上我有这个:

On my app.component.ts I have this:

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

我需要做什么来从我的ngOnInit调用这个方法让我可以使用方法之外的数据,所以我尝试了这个:

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();
}

但上面没有给我数据所以我错过了什么为了使用Angular?

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

推荐答案

修改你的第一个方法,只需从你的API调用返回一个异步结果,然后订阅方法本身。

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' });
}

和你 ngOnInit

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

这篇关于Javascript / Angular httpClient从url获取数据并传递外部方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆