我有一个服务,该服务将使用angularfire从Firestore获取数据。 一旦获得数据,我希望将值分配给像this.currentQuantity这样的全局变量。 但是this.currentQuantity的值在subscribe()方法之外变得不确定,而在subscribe方法内部变得正确。
我的component.ts文件
onBuy(){
this.stockService.GetOverviewStock().subscribe((response) => {
response.forEach((item) => {
if (item.StockName == this.selectedStockName) {
this.currentQuantity = item.Quantity;
this.currentTotalMoneySpent = item.TotalMoneySpent;
}
console.log(this.currentQuantity) // correct value from firestore
});
});
console.log(this.currentQuantity) // undefine
...doSomething(this.currentQuantity) // the value is undefine
}
我的service.ts文件从Firestore获取数据。
GetOverviewStock() {
return this.firestore
.collection<StockModel>("OverviewStock", (ref) => ref.orderBy("StockName", "asc"))
.valueChanges();
}
帮助,我刚接触过角度,还不太了解为什么以及如何解决。
答案 0 :(得分:3)
Observables
是处理async
请求的新方法。订阅Observables
与调用function
非常相似。但是Observables
的不同之处在于它们能够返回多个称为streams
的值。可观察对象不仅能够同步返回值,而且还能够异步返回值。
在您的情况下,首先执行第二个console.log(this.currentQuantity)
,而第二个subscription
并未用undefine
初始化,因此您首先获得subscription
,然后对ngOnInit() {
this.stockService.GetOverviewStock().subscribe((response) => {
response.forEach((item) => {
if (item.StockName == this.selectedStockName) {
this.currentQuantity = item.Quantity;
this.currentTotalMoneySpent = item.TotalMoneySpent;
}
console.log(this.currentQuantity) // correct value from firestore
this.logObservable();
});
});
}
logObservable() {
console.log(this.currentQuantity)
}
进行了评估。您可以尝试以下方法:
app.component.ts
this.logObservable()
这里async
已退出订阅,如果您选中它,答案是正确的。因此,您应该考虑 <androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<View
android:id="@+id/ratio_constraint"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintDimensionRatio="122:246"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="@id/ratio_constraint"
app:layout_constraintStart_toStartOf="@id/ratio_constraint"
app:layout_constraintTop_toTopOf="@id/ratio_constraint"
tools:text="The TextView which can extend the layout" />
</androidx.constraintlayout.widget.ConstraintLayout>
的行为并执行类似的操作。
答案 1 :(得分:0)
它将按预期工作,除了GetOverviewStock()
必须先触发(因此将调用订阅和值分配)。最初,这些字段实际上将是未定义的(或具有您设置的其他初始值)
答案 2 :(得分:0)
您正在使用异步,因此必须在...doSomething(this.currentQuantity)
内部调用subscribe()
(例如@ ng-hobby所说)。简而言之,您无法像代码一样获得this.currentQuantity
之外的subscribe()
值,您可以阅读有关异步调用的更多信息以了解原因。