简体   繁体   中英

Angular 4 does not update an array when I push some data from a response after post

I have a POST method that the user will post an data to the server. The POST method is successfully working but I don't want to refresh my page after posting instead I want to update the array that I am looping through.

I want to update that array using the push method of an array base from the response of the post. My end goal here is to update the posts without refreshing the page like a real time update.

So here is what I have done so far.

posts: any = [];
fake_post: any = [];
success: boolean = false;

In my constructor

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))
    });

and in my submit() method:

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.')
    }
  }

when I want console.log the array after the push method of an array this is what I got:

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

That indexOf 4 id in the array is the post that I had created but I didn't return an object.

So how would I deal with this?

And as a bonus how can I refactor my promises using async and await ?

Appreciate if someone could help. Thanks in advance.

Use Observable instead of promise and subscribe to them. Refer the below thread for a possible solution: Angular 2 not updating when array is updated

In order to reflect the data changes on the template, you need to use detect changes,

 constructor(private cdr:ChangeDetectorRef) {

and apply the following once you push the data

  this.cdr.detectChanges();

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM