![of of](https://c1.lmlphp.com/image/static/default_avatar.gif)
本文介绍了Angular 6 Observables-从.subscribe()函数提取数据并在其他地方使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用可观察的东西撞到墙上.我可以找到的几乎所有文档都使用较旧的 rxjs
语法.
我有一个可观察到的API调用.我在其他地方调用它并进行预订-尝试使用此 GET
请求中的数据填充表.
如果我只是 console.log
我的 getData
函数,它将记录订阅而不是我的数据.我可以在 .subscribe
函数中成功地console.log data
,但是我想在 .subscribe() data
/code>.
如何从 .subscribe()
函数中提取 data
并在其他地方使用?还是必须将我所有的逻辑都包含在 .subscribe()
函数中才能使用 data
?
getData2(){返回this.m_dbService.get('api/myApiPath').subscribe(数据=>(console.log(data)),//这正确记录了我的数据.如何从此处提取数据"并实际使用?错误=>{投掷错误},()=>console.log(完成"));}workbookInit(args){var datasource = this.getData2();//这将返回订阅,并且不起作用.}
解决方案
只需从 getData()
返回HTTP请求,然后在 workbookInit
函数中进行预订即可.
>
getData2(){返回this.m_dbService.get('api/myApiPath')}workbookInit(args){this.getData2().subscribe(数据=>{var数据源=数据},错误=>{投掷错误},()=>console.log(完成")}
I'm banging my head against the wall with observables. Almost all of the documentation I can find is in the older rxjs
syntax.
I have an API call which is an observable. I'm calling it elsewhere and subscribing to it - trying to populate a table with the data from this GET
request.
If I simply console.log
my getData
function, it logs the subscription rather than my data.I can successfully console.log data
within the .subscribe
function, but I want to use data
outside of .subscribe()
.
How do I extract data
out of the .subscribe()
function and use it elsewhere? Or, must all of my logic be contained within the .subscribe()
function to use data
?
getData2() {
return this.m_dbService.get('api/myApiPath').subscribe(
data => (console.log(data)), //This properly logs my data. How to extract `data` out of here and actually use it?
error => { throw error },
() => console.log("finished")
);
}
workbookInit(args){
var datasource = this.getData2(); // this returns the subscription and doesn't work.
}
解决方案
just return the HTTP req from getData()
and subscribe it inside the workbookInit
function.
getData2() {
return this.m_dbService.get('api/myApiPath')
}
workbookInit(args){
this.getData2().subscribe(
data => {
var datasource = data
},
error => { throw error },
() => console.log("finished")
}
这篇关于Angular 6 Observables-从.subscribe()函数提取数据并在其他地方使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!