【问题标题】:Value of object don't change after post resquest发布请求后对象的值不会改变
【发布时间】:2018-07-20 15:05:17
【问题描述】:

这种情况已经不是第一次了。我通过http调用post resquest:

this.http.post('url', this.simpleFilter)
  .map((response: Response) => response.json())
  .subscribe(data => {
    if (data.data) {
      this.simpleFilter = data.data;
      console.log(this.simpleFilter.type);
      console.log(this.simpleFilter);
      this.emissorFilter.next(this.simpleFilter);
    } else {
        swal(data.error, data.message, 'error');
    }

  },
  error => swal(data.error, data.message, 'error'));

我在哪里 console.log(this.simpleFilter.type) 打印类型是

1

但是当console.log(this.simpleFilter);打印对象的类型是什么

0

它发生的另一次

附:类型对象是一个枚举

为什么会这样?

【问题讨论】:

    标签: angular http-post subscription


    【解决方案1】:

    如果您还发布了预期的输出并更详细地解释了所有内容,这确实会改善您的问题,但我很确定我理解您的问题。

    这是因为当您记录一个原始属性(数字或字符串)时,您会获取当前存在的值并将其输出。当您打印一个对象时,您有一个链接显示在开发人员的工具中。因此控制台中对象的属性会随着数据的变化而更新。这导致了差异。您可以尝试将两个 console.log 语句包装在 setTimeout 中,并延迟以查看输出是否不同。

    【讨论】:

    • 好的,我会尝试,但是当我使用 this.ememberFilter.next(this.simpleFilter) 时,我在订阅时收到的每个对象都有类型 0,独立于接收到的类型。
    • 好吧,我试过了,但是没有解决我的问题。当登录控制台或订阅 emissorFilter 时,类型保持为 0
    【解决方案2】:

    要在订阅时正确设置我的对象,我必须将它包装在另一个对象中。 例如:

    // in Service
    let wrappedFilter = {
      type: this.simpleFilter.type,
      filter: this.simpleFilter
    }
    this.emissorWrappedFilter.next(wrappedFilter);
    

    在订阅中我重放了对象:

    // in Component
    this.service.emissorWrappedFilter.subscription ( wf => {
      this.simpleFilter = wf.filter;
      this.simpleFilter.type = wf.type;
      (...)
    });
    

    我不知道这是否是最好的方法,但它有效!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-13
      • 2016-02-09
      • 2015-03-01
      • 2017-08-14
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 2018-09-02
      相关资源
      最近更新 更多