所以我有一个<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.bottomappbar.BottomAppBar
android:id="@+id/bottomAppBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="bottom"
app:fabAlignmentMode="end"
app:fabCradleMargin="8dp"
app:hideOnScroll="true"
android:layout_gravity="bottom"
android:backgroundTint="@color/white"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#212121"
app:tint="@null"
android:onClick="addNewNote"
app:fabSize="normal"
android:src="@drawable/ic_add"
app:borderWidth="0dp"
app:layout_anchor="@id/bottomAppBar"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
链:
then
第二个 ngOnInit() {
this.contentfulService.getExhibits()
.then(exhibits => this.exhibits = exhibits)
.then(exhibits => {console.log("0", exhibits[0])})
.then(exhibits => {console.log("1", exhibits[1])});
}
出现错误Uncaught (in promise):
。我不知道为什么会这样吗?谢谢!
答案 0 :(得分:1)
这里的几个问题:
您已分配this.exhibits = exhibits
,但未返回任何内容。因此,下一个.then()
exhibits
无法访问,从而导致问题。您可以像这样返回它:
.then(exhibits => {
this.exhibits = exhibits
return exhibits
})
尽管您可能没有在任何地方使用this.exhibits
,但可能不需要这样做。因此,您可以像这样简单地返回exhibits
:
.then(exhibits => exhibits)
尽管这也是不必要的,您可以将其删除并访问exhibits
数组,例如:
this.contentfulService.getExhibits()
.then(exhibits => {
if(exhibits && exhibits.length){
console.log("0", exhibits[0] || {})
console.log("1", exhibits[1] || {})
}
})
或者,如果您在其他地方使用this.exhibits
,则可以使用:
this.contentfulService.getExhibits()
.then(exhibits => {
this.exhibits = exhibits
return exhibits
})
.then(exhibits => {
if (exhibits && exhibits.length) {
console.log("0", exhibits[0] || {})
console.log("1", exhibits[1] || {})
}
})
此外,尽管进行ajax调用时始终使用正确的错误处理,即catch
,即使在ajax调用在链中失败之后,这也有助于完成新动作,例如:
this.contentfulService.getExhibits()
.then(exhibits => {
this.exhibits = exhibits
return exhibits
})
.then(exhibits => {
if (exhibits && exhibits.length) {
console.log("0", exhibits[0] || {})
console.log("1", exhibits[1] || {})
}
}).catch((error) => {
console.error("Error: " + error);
})
答案 1 :(得分:0)
从第一个.then
到第二个都不返回任何内容,因此exhibits
在第二个.then
中将不存在(第三个都不存在)。>
您应该从第一个.then
返回它,或者从this.exhibits
记录它。
类似这样的东西:
ngOnInit() {
this.contentfulService.getExhibits()
.then(exhibits => {
this.exhibits = exhibits
return exhibits
})
.then(exhibits => {
console.log("0", exhibits[0])
return exhibits
})
.then(exhibits => {
console.log("1", exhibits[1])
});
}
也许更好
ngOnInit() {
this.contentfulService.getExhibits()
.then(exhibits => this.exhibits = exhibits)
.then(exhibits => console.log("0", this.exhibits[0]))
.then(exhibits => console.log("1", this.exhibits[1]));
}