【问题标题】:Delete empty row created by subscription to service on ngOnInit()删除在 ngOnInit() 上订阅服务创建的空行
【发布时间】:2019-05-19 23:15:26
【问题描述】:

我有一个材料数据表,用户可以自己填写和清空。进入表的数据由服务触发,我在表组件中使用ngOnInit() 对其进行了初始化。

代码:

  ngOnInit() {
    this._AS.transaction$.subscribe( transaction => {
        this.transaction = transaction;
        this.temp = this.dataSource.data.slice();
        this.temp.push(this.transaction); // Stop this call on init somehow?
        this.dataSource.data = this.temp;
        this.ref.detectChanges();
        console.log(this.transaction);
      }
    );
  }

问题是:总是有一个空行被调用this.temp.push(this.transaction) 推送。有没有办法第一次停止这个呼叫或类似的事情?

【问题讨论】:

    标签: typescript service angular7 ngoninit


    【解决方案1】:

    为什么它是空的,因为“交易”是? 那么为什么不直接使用 if 查询呢? 或者您可以在父组件中声明一个(布尔)变量,并在您第一次点击 ngOnInit 时将其设置为 true

    constructor( public parentComponent: ParentComponent) {
    
    }
    
    ngOnInit() {
      if(parent.isInitialized) {
        this._AS.transaction$.subscribe( transaction => {
          this.transaction = transaction;
          this.temp = this.dataSource.data.slice();
    
          if(parent.isInitialized) {
            this.temp.push(this.transaction); // Stop this call on init somehow?
          } else {
            parent.isInitialized = true;
          }
    
          this.dataSource.data = this.temp;
          this.ref.detectChanges();
          console.log(this.transaction);
        } );
    }
    

    【讨论】:

    • 我刚试过。它没有用。空行消失了,布尔值设置为真。但是,如果我想将数据添加到表中,它不会显示该数据。
    • 哦,好吧,如果你在订阅闭包中执行 if(parent.isInitialized 怎么办?见编辑
    【解决方案2】:

    我只是使用了另一种方法: 将空事务推入表后,我将其弹出,以便表再次为空。推送数据现在可以正常工作了。

      ngOnInit() {
          this._AS.transaction$.subscribe(transaction => {
              this.transaction = transaction;
              this.temp = this.dataSource.data.slice();
              this.temp.push(this.transaction);
              this.dataSource.data = this.temp;
              this.ref.detectChanges();
            }
          );
          this.temp = this.dataSource.data.slice();
          this.temp.pop();
          this.dataSource.data = this.temp;
          this.ref.detectChanges();
      }
    

    【讨论】:

      猜你喜欢
      • 2017-05-13
      • 2020-08-21
      • 2019-10-25
      • 1970-01-01
      • 2022-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-01
      相关资源
      最近更新 更多