[英]how to post an array with some object when I have an array with id, using angular
[英]Angular 4 does not update an array when I push some data from a response after post
我有一個POST方法,用戶會將數據發布到服務器。 POST方法可以成功工作,但是我不想在發布后刷新頁面,而是想更新循環遍歷的數組。
我想從帖子的響應中使用數組基礎的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
方法之后的數組時,這就是我得到的:
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是我創建的帖子,但是我沒有返回對象。
那么我該如何處理呢?
作為獎勵,我如何使用異步和等待來重構我的諾言 ?
感謝有人可以幫忙。 提前致謝。
使用Observable而不是promise並訂閱它們。 請參閱以下線程以獲取可能的解決方案: 更新數組時,Angular 2不更新
為了反映模板上的數據更改,您需要使用檢測更改,
constructor(private cdr:ChangeDetectorRef) {
並在推送數據后應用以下內容
this.cdr.detectChanges();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.