【发布时间】:2021-06-05 12:02:45
【问题描述】:
我在这里处于一个松散的结局,并试图了解角度订阅的工作流程。
我调用 API 并在响应中将数据设置在 behaviorSubject 中。这样我就可以在我的应用程序中订阅该数据。
通常我会在我的模板中使用异步管道,因为它会更干净,它会为我清除所有订阅数据。
所有方法都属于同一个类方法。
我的第一次尝试.....
exportedData: BehaviourSubject = new BehaviourSubject([]);
exportApiCall(id) {
this.loadingSubject.next(true)
this.api.getReport(id).pipe(
catchError((err, caught) => this.errorHandler.errorHandler(err, caught)),
finalize(() => => this.loadingSubject.next(false))
).subscribe(res => {
this.exportedData.next(res)
})
}
export(collection) {
let x = []
this.exportCollection(collection.id); /// calls api
this.exportedData.subscribe(exportData => {
if(exportData){
x = exportData
}
})
}
console.log(x)//// first time it's empthy, then it's populated with the last click of data
/// in the template
<button (click)="export(data)">Export</button>
我的问题是……
有一个具有不同 ID 的按钮列表。每个 ID 都进入 API 并返回某些数据。当我单击时,控制台日志首先给出一个空白数组。然后在我得到上一个(我最初点击的那个)数据集之后。
我显然没有正确理解订阅、管道和行为主题。我知道我得到了一个空白数组,因为我将行为主题设置为一个空白数组。
我的另一个尝试
export(collection) {
let x = []
this.exportCollection(collection.id).pip(tap(res => x = res)).subscribe()
console.log(x) //// get blank array
}
exportApiCall(id) {
return this.api.getReport(id).pipe(
catchError((err, caught) => this.errorHandler.errorHandler(err, caught))
)
}
【问题讨论】:
-
在第一个示例中,我不知道您的
console.log(x)到底在哪里?它在类方法之外的某个地方?此外,您的按钮有(click)="export(data)",但没有给出这样的方法。 -
方法已更新。控制台。你可以在方法中看到。 res 分配给 x。然后我在方法之外对 x 进行控制台,因为我想获取数据
标签: javascript angular rxjs observable subscription