Kyl*_*lla 3 asynchronous subscribe observable rxjs angular
我用可观察的东西撞在墙上。我可以找到的几乎所有文档都使用较旧的rxjs
语法。
我有一个可观察到的API调用。我在其他地方调用它并进行预订-尝试用此GET
请求中的数据填充表。
如果仅是console.log
我的getData
函数,它将记录订阅而不是数据。我可以data
在.subscribe
函数内成功console.log ,但是我想在data
之外使用.subscribe()
。
我如何提取data
出来的.subscribe()
功能和其他地方使用它?还是必须将我所有的逻辑都包含在.subscribe()
要使用的函数中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.
}
Run Code Online (Sandbox Code Playgroud)
只需返回 HTTP 请求getData()
并在workbookInit
函数内订阅它。
getData2() {
return this.m_dbService.get('api/myApiPath')
}
workbookInit(args){
this.getData2().subscribe(
data => {
var datasource = data
},
error => { throw error },
() => console.log("finished")
}
Run Code Online (Sandbox Code Playgroud)
您可能想要做的是Observable
用数据填充另一个数据,以便您可以在项目的其他位置访问它,而无需多次调用API。
为此,您创建了一个所谓的Subject
(在本例中为BehaviorSubject
),并且可以在API调用返回响应时用数据填充该数据。
然后,为了在其他地方访问此数据,您可以创建一个“ get”函数以在需要数据时返回Subject
(本身就是Observable
)。
这是一个例子:
my-data.service.ts
myData: BehaviorSubject<number> = new BehaviorSubject<number>(0);
callApi() {
this.dbService.get('apiUrl').subscribe(
(data) = > this.myData.next(data) // Assuming data is a 'number'
);
}
getMyData() {
return this.myData.asObservable();
}
Run Code Online (Sandbox Code Playgroud)
现在在组件中使用它:
this.myService.getMyData().subscribe(
(data) => { /* Use the value from myData observable freely */ }
);
Run Code Online (Sandbox Code Playgroud)
或者,您可以依赖Angular异步管道(这是处理代码中可观察对象的一种非常方便的方法)。