【发布时间】:2018-07-12 01:24:14
【问题描述】:
我有一个 POST 方法,用户可以将数据发布到服务器。 POST 方法已成功运行,但我不想在发布后刷新我的页面,而是想更新我正在循环的数组。
我想从帖子的响应中使用 array 基础的 push 方法更新该数组。我的最终目标是更新帖子,而不像实时更新那样刷新页面。
这就是我到目前为止所做的。
posts: any = [];
fake_post: any = [];
success: boolean = false;
在我的构造函数
events.subscribe('post:created-successfully', (data) => {
const promise = Promise.resolve(data)
promise.then(() => this.success = true).then(() => this.fake_post = [])
.then(() => setTimeout(() => { this.success = false }, 1000))
.then(data => this.posts.push(data))
.then(() => console.log(this.posts))
});
在我的submit() 方法中:
submit() {
this.showLoader();
if (this.form.value.title && this.form.value.author) {
this.loading.dismiss();
this.data = this.form.value;
console.log(this.data);
this.view.dismiss( this.data );
this.postApiProvider.createPost(this.data).then((response : addReponse) => {
console.log('Provider response', response);
this.data = response;
})
.then(() => this.events.publish('post:created-successfully', this.data))
.then(() => this.presentToast(this.data))
.catch(err => console.log(err));
} else {
console.log('Something went wrong.')
}
}
当我想要 console.log 数组的 push 方法之后的 array 时,这就是我得到的:
0
:
{title: "Async and Await", author: "Jayz", id: 1}
1
:
{title: "Promises", author: "Jayz", id: 2}
2
:
{title: "Callbacks", author: "Jayz", id: 3}
3
:
{title: "1234", author: "1234", id: 4}
4
:
135
数组中的indexOf 4 id 是我创建的帖子,但我没有返回对象。
那我该如何处理呢?
作为奖励,我如何使用 async 和 await 重构我的 promise?
如果有人可以提供帮助,我们将不胜感激。 提前致谢。
【问题讨论】: