【问题标题】:Reset a array before subscribe angular2在订阅 angular2 之前重置数组
【发布时间】:2017-04-17 13:19:22
【问题描述】:

我正在尝试在快速会话中使用多个过滤器,我正在获取数组中的先前数据以及新数据。如何删除之前的数据。

组件.ts

ngOnInit() {
  this.vehicleAttribute = JSON.parse(sessionStorage.getItem('vehicleAttributes'));
  const data: ProductCatalogPostData = {
    vehicleModelAttributes: this.vehicleAttribute.vehicleModels[0].modelAttributes,
    role: 'vehicle owner',
    planType: this.planType
  };
  const page: ProductCatalogPostPagination = {
    page: this.pageNo
  };
  this.productCatalogService.compatibleProducts(data, page.page).subscribe(
    response => {
      for (let i = 0; i < response.products.length; i++) {
        this.lists.push(response.products[i]);
      }
      this.pageCount = response.totalCount;
    },
    error => {
      console.log(error);
    }
  );
}

关于过滤功能,我正在尝试使列表为空

onSelectedChange($event) {
  this.lists = [];
  this.planType = $event[0]
  this.ngOnInit();
}

但我仍然是以前的订阅数据以及新数据。任何输入都非常感谢

【问题讨论】:

  • 从过滤函数调用ngOnInit肯定不行。你永远不应该打电话给它。关键是 Angular 调用它。
  • 您为什么期望不同的数据? productCatalogService.compatibleProducts 可能会返回相同的结果,因为您没有任何参数化。
  • @AluanHaddad 在selectedChange 函数上我得到了我的planType 值,所以我用新的planType 值调用了http 请求。所以这就是我打电话给ngOnInit() 的原因(如果有其他方法,请指导)并且我确实得到了关于我的 planType 值更改的不同数据。我在没有任何帮助的情况下使用了 debounce 功能
  • 不要重用初始化逻辑并通过在一个方法中更改可变属性来进行通信,以便可以在另一个方法中读取它,而是将初始化逻辑提取到一个单独的方法中,该方法采用 planType作为参数。从ngOnInitonSelectedChange 调用新方法。您应该进行此更改,因为您当前的方法很脆弱且不明显,并且通过滥用框架挂钩的名称 ngOnInit 来实现多种目的,显然是代码重用的错误方面。

标签: angular typescript angular2-routing angular2-template


【解决方案1】:

你可以使用如下的do操作符来实现

this.productCatalogService.compatibleProducts(data, page.page)
  .do(data => {
       if(isEmpty(data)) {
          this.lists= new Array();
       }
   })
  .subscribe(response => {
      for (let i = 0; i < response.products.length; i++) {
        this.lists.push(response.products[i]);
      }
      this.pageCount = response.totalCount;
    },error => {
      console.log(error);
    });

【讨论】:

    【解决方案2】:

    我不太明白你为什么要迭代,为什么不呢

    this.list = response.products
    

    但如果你有理由不这样做,那么你可以复制元素

    this.list = [].concat(response.products)
    

    如果您出于某种原因不想清洁,请一次性将它们全部推入

    this.list.push(...response.products)
    

    最后一个将等于:

    Array.prototype.push.apply(this.list, response.products)
    

    【讨论】:

    • 我使用push功能的原因是过滤器可以分页吗。
    • 对不起,我听不懂你在说什么
    猜你喜欢
    • 1970-01-01
    • 2016-11-17
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 2018-03-13
    • 2016-05-17
    相关资源
    最近更新 更多