【问题标题】:Angular 4 does not update an array when I push some data from a response after post当我在发布后从响应中推送一些数据时,Angular 4 不会更新数组
【发布时间】: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

如果有人可以提供帮助,我们将不胜感激。 提前致谢。

【问题讨论】:

    标签: arrays angular object


    【解决方案1】:

    使用 Observable 代替 Promise 并订阅它们。 请参阅以下线程以获取可能的解决方案: Angular 2 not updating when array is updated

    【讨论】:

    • 谢谢!我将使用 observables 代替。
    • 顺便问一下。为什么我的数组推送不起作用,它只返回与现有对象相同的对象。所以是的,我收到了一个新的 GET 请求,页面没有刷新,但有一点闪烁。
    【解决方案2】:

    为了在模板上反映数据的变化,需要使用detect changes,

     constructor(private cdr:ChangeDetectorRef) {
    

    并在推送数据后应用以下内容

      this.cdr.detectChanges();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 2021-04-12
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      相关资源
      最近更新 更多