无法将数组长度获取到Angular中的变量

时间:2018-09-19 05:50:19

标签: angular

我有一个带有搜索功能的角度项目。我需要在搜索中打印搜索项计数。为了进行搜索,我正在使用搜索词过滤JSON对象,并创建一个名为filterarray的新数组。然后,我选择filterarray的长度并进行打印。但是我需要在另一个名为search-count.component的组件中进行打印。为此,我使用了一个称为count.service的可共享服务。问题是,当我在HTML绑定中打印数组长度时,它将正确打印,但搜索计数组件的值为0 alywas。

Search-Component.ts:

export class SearchResultComponent implements OnInit {

  _postsArray: JsoncallItem[] = []; //JSON-array
  value: string = ''; //search-term
  filterarray: any = []; //filtered-array
  count:string; //filtered-array-length

  constructor(private data: SendDataService, private tot: CountService){}

  getData(){
    this.data.currentValue.subscribe(value => {this.value = value;
      this.showData();
    })
  }

  showData(){
    if (this.value != null){
      this.filterarray=
        this._postsArray.filter(f => 
          f.title.toLowerCase()
            .includes(this.value.toLowerCase()))
              .map(searchname=>searchname)
    }
  }

  newCount(){
    this.tot.currentCount.subscribe(count => this.count = count);
    this.tot.changeCount(this.filterarray.length);
  }

    ngOnInit(): void{
    this.getData();
    this.newCount();
  }

}

Search-Component.html:

{{filterarray.length}}
//show correct length

search-count.ts:

export class SearchCountComponent implements OnInit {

  count: any;

  constructor(private tot: CountService) {}

  ngOnInit(): void {
      this.tot.currentCount.subscribe(count => this.count = count);
  }
}

search-count.html:

{{count}}
//show 0 always

count.service

export class CountService {

  private countSource = new BehaviorSubject('');
  currentCount = this.countSource.asObservable();

  constructor() { }

  changeCount(count: string) {
    this.countSource.next(count)
  }
}

2 个答案:

答案 0 :(得分:0)

我认为您比使用OnInit更好地使用AfterViewInit,因此只要更改filterarray的长度,该值就会更新 您可以像这样使用AfterViewInit

 ngAfterViewInit(){
      this.tot.currentCount.subscribe(count => this.count = count);
  }

答案 1 :(得分:0)

我知道了。问题是我在this.newCount();中调用ngOnInit(),以便它在更新filterarray之前执行。通过将this.newCount();移动到getData()函数中来解决,如下所示:

getData(){
  this.data.currentValue.subscribe(value => {this.value = value;
    this.showData();
    this.newCount();
  })
}

ngOnInit(): void{
this.getData();

}