【问题标题】:angular 2 custom sort pipe help me plaseangular 2 custom sort pipe 请帮帮我
【发布时间】:2018-05-02 05:09:51
【问题描述】:

 *ngFor="let match of virtual | groupby : 'gameid'

我有这样的代码。我有一个管道。 gameid 就像 23342341 。

我需要按 gameid 对这个数组进行 asc 排序。帮帮我,伙计们。我需要什么样的代码。

import { Pipe, PipeTransform, Component, NgModule} from '@angular/core';

/**
 * Generated class for the GroupbyPipe pipe.
 *
 * See https://angular.io/api/core/Pipe for more info on Angular Pipes.
 */
@Pipe({
  name: 'groupby',
})
export class GroupbyPipe implements PipeTransform {
  /**
   * Takes a value and makes it lowercase.
   */
   transform(array: Array<string>, args: string): Array<string> {
        if (array !== undefined) {
            array.sort((a: any, b: any) => {
                if ( a[args] < b[args] ){
                    return -1;
                } else if ( a[args] > b[args] ) {
                    return 1;
                } else {
                    return 0;   
                }
            });
        }
        return array;
    }

}

它是我的管道

我在 google 中找到了代码,但它不起作用。任何人都会帮助我如何通过gameid(整数)对管道上的数组进行排序?

【问题讨论】:

  • 您在控制台上是否收到任何错误?一切似乎都很好,请检查我的工作版本stackblitz.com/edit/angular-filter
  • @PrithiviRaj 是的。它说 TypeError: Cannot read property 'sort' of undefined
  • 数据是否在没有管道的情况下进入循环?我在共享代码中没有发现任何问题。尽可能共享 TS 文件和 HTML 文件
  • @PrithiviRaj 是的,我可以分享,但我不认为你可以阅读我的代码,它很大。管道正在另一个 ngFor 工作,但 ngfor 的数据来自本地。这个 issies 版本是来自 this.http.get 的数据,大约是 40 倍。但是当我打开页面数据时不存在。您有什么建议吗?
  • 1.尝试不使用管道并查看数据是否以 HTML 格式显示。 2. 如果数据没有进入 HTML,检查 HTTP 请求是否正在发生,并检查 virtual 中的值

标签: typescript ionic2 angular2-routing angular2-template angular2-directives


【解决方案1】:

我添加了 changeDetectorRef 来检测本地的变化。有时订阅内部的数据更改不会反映。下面是我的带有 changeDetectorRef 和 slice 的示例代码。两者都用,看看。 This is my working version here

import { Component, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
 term:string = "";
  topics = [
    {type:"NonFiction", name:"Titanic", num:2},
    {type:"Fiction", name:"Avatar", num:1},

    {type:"Tragedy", name:"MotherIndia",num:5},
  ];
  constructor(public ref : ChangeDetectorRef) { }

  ngOnInit() {
    this.addTopic();
  }

  addTopic(){
    setTimeout(()=>{
      console.log("triggered");
      this.topics.push({type:"share", name:"MotherIndia",num:3});
      this.topics=this.topics.slice();
      this.ref.detectChanges();
    },5000)
  }
}

【讨论】:

  • 向我展示如何根据 http 请求将数据插入到虚拟数组中
  • 您的示例中缺少重要部分
  • 我缩短了ts。
  • 我已经用 changeDetectorRef 更新了代码。也试试吧。
  • 你需要分享网址我认为。不会改变任何东西
猜你喜欢
  • 2017-08-14
  • 1970-01-01
  • 2022-01-23
  • 2011-01-08
  • 1970-01-01
  • 2022-11-15
  • 2013-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多