如何正确排序数组?

时间:2019-01-03 10:52:49

标签: angular typescript

我有一个这样的模型:

export class ProductAvarageRating {
  productId: number;
  avarageRating: any;
}

在父级中,我从未排序的API获取该数组。我像这样初始化html中的组件:

<app-my-products-ratings
          [ratings]="ratings"
        ></app-my-products-ratings>

i调用组件:

export class MyProductsRatingsComponent implements OnInit {
  @Input() ratings: ProductAvarageRating[] = []; //data from parent

  constructor() {}

  ngOnInit() {
    this.ratings.sort((a, b) =>
      a.productId > b.productId ? 1 : b.productId > a.productId ? -1 : 0
    );
  }
}

我的问题是,为什么我在调用ratings函数时没有对sort进行排序?我在这里做错了什么?也许我需要在其他地方调用sort函数?

编辑

我剪切的不是必需信息,但是我的孩子部分有两个@Input()

export class MyProductsRatingsComponent implements OnInit {
  @Input() ratings: ProductAvarageRating[] = []; //data from parent
  @Input() watchedProducts: WatchedProduct[] = [];
  //same staf as above

和父母的html:

<app-my-products-ratings
          [watchedProducts]="watchedProducts"
          [ratings]="ratings"
        ></app-my-products-ratings>

EDIT2

根据Patryk的回答,我在set ratings(...)...上遇到了错误:

  

“ set”访问器参数不能具有初始化程序。

EDIT3

我的Parent有两个Childs,我用parent's html称呼它:

<div>
    <app-my-products-watched
      [watchedProducts]="watchedProducts"
    ></app-my-products-watched>

    <app-my-products-ratings
      [watchedProducts]="watchedProducts"
      [ratings]="ratings"
    ></app-my-products-ratings>
</div>

1 个答案:

答案 0 :(得分:4)

我建议使用set方法@Input()(在ngOnInit之后,有可能将输入传递给孩子)

_ratings: ProductAvarageRating[] = [];

@Input()
set ratings(ratings: ProductAvarageRating[]) {
   this._ratings = ratings;
   this._ratings=  this._ratings.sort((a, b) =>
      a.productId > b.productId ? 1 : b.productId > a.productId ? -1 : 0
   );
}

感谢每次输入更改时都会调用它。

编辑:

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

export class ProductAvarageRating {
  productId: number;
  avarageRating: any;
}

@Component({
  selector: 'hello',
  template: `
      <ng-container *ngFor="let rating of _ratings">
          <pre>{{rating | json}}</pre>
      </ng-container>
  `
})
export class HelloComponent  {
  @Input() name: string;

  _ratings: ProductAvarageRating[] = [];

  @Input()
  set ratings(ratings: ProductAvarageRating[]) {
    this._ratings = [...ratings];
    this._ratings=  this._ratings.sort((a, b) =>
        a.productId > b.productId ? 1 : b.productId > a.productId ? -1 : 0
    );
  }
}

//in parent
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<hello  [ratings]="ratings"></hello>
<p>
  Start editing to see some magic happen :)
</p>`
})
export class AppComponent  {
  name = 'Angular';

  ratings = [{productId: 2}, {productId: 1}];
}