【问题标题】:Return data filtered on ngOnInit返回在 ngOnInit 上过滤的数据
【发布时间】:2017-12-09 01:57:52
【问题描述】:

在我的 component.ts 中,我有一个从服务返回数据并将其保存到 myPosts 对象的函数。该函数称为getData(); 我想要做的是在 ngOnInit() 调用之前按日期过滤 getData。

所以最初我的表格会显示上个月的所有帖子。 然后我应该能够更改另一个函数的日期并过滤不同的范围。

我的过滤功能在控制器上。 获取数据后如何调用过滤器函数,以便最初在 ngOnInit 上过滤数据?

public getData() {
this.postsService.getAllPosts().subscribe(results => {
  this.myPosts= results['data'];    
});
}

filterByDate(){
  const monthAgo= moment().subtract(1, 'month');
   this.myPosts= this.myPosts.filter(item => moment(item.SubmittedDate).isAfter(monthAgo));
}

【问题讨论】:

    标签: angular angular5


    【解决方案1】:

    创建一个方法来过滤然后分配数据,如下所示,

    filterByDate(myPosts){
      const monthAgo= moment().subtract(1, 'month');
       return myPosts.filter(item => moment(item.SubmittedDate).isAfter(monthAgo));
    }
    

    在您的 onInit 函数中,使用该函数

    public getData() {
    this.postsService.getAllPosts().subscribe(results => {
      this.myPosts= this.filterByDate(results['data']);    
    });
    }
    

    【讨论】:

    • 谢谢。但是我在哪里调用它,以便这些数据是最初返回的数据?目前在 ngOnInit 我调用 getData();
    • MyPosts 会有过滤结果,是的。但是,如果用户更改要显示的日期范围?我在 ngModelChange 上调用 filterByDate 并且我没有将 myPosts 作为输入。我想我必须使用两个单独的函数。
    【解决方案2】:

    在构造函数中调用getData()方法,然后在ngOnInIt中使用过滤函数filterByDate()

    export class SomeClass implements OnInIt {
          public getData() {
            this.postsService.getAllPosts().subscribe(results => {
              this.myPosts = this.filterByDate(results['data']);
            });            
          }
          public filterByDate(myPosts){
              const monthAgo = moment().subtract(1, 'month');
              return myPosts.filter(item =>  
              moment(item.SubmittedDate).isAfter(monthAgo));
            }
          constructor() {
            this.posts = this.getData();
          }
          ngOnInIt() {
            this.filterPosts = this.filterByDate(posts);
          }
        }
    

    【讨论】:

    • 我很困惑。是否必须将 myPosts 作为函数的输入参数提供?它们是在控制器中声明的。问题是我有 filterByDate(startDate,endDate,lastMonth) ,它在 ngModelChange 上被调用。如果 lastmonth==true,那么我过滤上个月。因为当用户选择要过滤的日期范围时,我希望能够使用相同的功能。但是我在上个月已经过滤了初始结果时遇到了问题。
    猜你喜欢
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2020-08-23
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多