So I have a chain of then
:
ngOnInit() { this.contentfulService.getExhibits().then(exhibits => this.exhibits = exhibits).then(exhibits => {console.log("0", exhibits[0])}).then(exhibits => {console.log("1", exhibits[1])}); }
I get the error Uncaught (in promise):
at the second console.log
. I can't figure out why that is? Thank you!
Few issues here:
You have assigned this.exhibits = exhibits
but have not returned anything. Thus on next .then()
exhibits
is not accessible and thus causing the issue. You can return it like:
.then(exhibits => {
this.exhibits = exhibits
return exhibits
})
Though this might not be needed as you not using this.exhibits
anywhere. So, you can simply return exhibits
like:
.then(exhibits => exhibits)
Though this is also unnecessary and you can simply remove it and access exhibits
array like:
this.contentfulService.getExhibits()
.then(exhibits => {
if(exhibits && exhibits.length){
console.log("0", exhibits[0] || {})
console.log("1", exhibits[1] || {})
}
})
Or, if you are using this.exhibits
elsewhere, then you can use:
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] || {})
}
})
Also, while making ajax calls always use proper error handling, ie a catch
, which is useful to accomplish new actions even after an ajax call has failed in the chain like:
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);
})
You're not returning anything from the first .then
to the second one, so exhibits
won't exists in your second .then
(neither in your third one).
You should return it from the first .then
, or logging it from this.exhibits
.
Something like this:
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])
});
}
or maybe better
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]));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.