2
我試圖效仿AngularJS中的OrderBy。Angular 4 FilterBy Pipe
鑑於這種數組。我需要通過car_category過濾汽車。
[
{
"car_category": 3,
"name": "Fusion",
"year": "2010"
},
{
"car_category": 2,
"name": "Mustang",
"year": "2010"
},
{
"car_category": 3,
"name": "Fiesta",
"year": "2010"
},
]
這裏是我的代碼看起來到目前爲止
car.component.html
<div *ngIf="products">
<ul *ngFor="let product of products | filterBy: car_category">
<li>{{car.name}}</li>
</ul>
</div>
car.component.ts
import { Component, OnInit } from '@angular/core';
import { CarService } from '../car.service';
import { ICars } from '../ICars';
import { FilterByPipe } from '../filter-by.pipe';
@Component({
selector: 'app-home-page',
templateUrl: './car.component.html',
styleUrls: ['./car.component.css']
})
export class CarComponent implements OnInit {
cars: Array<ICars>;
errorMessage: string;
filteredCars: any;
car_category= 3;
constructor(private _carService: CarService) { }
ngOnInit() {
this._carService.getCars()
.subscribe(
cars => this.cars = cars,
error => this.errorMessage = error
);
}
}
filet- by.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filterBy'
})
export class FilterByPipe implements PipeTransform {
transform(value, args) {
if (!args[0]) {
return value;
} else if (value) {
return value.filter(item => {
// tslint:disable-next-line:prefer-const
for (let key in item) {
if ((typeof item[key] === 'string' || item[key] instanceof String) &&
(item[key].indexOf(args[0]) !== -1)) {
return true;
}
}
});
}
}
}
如何我管需要進行重構?
UPDATE 這就是我的管道現在的樣子。注意,這輛車是一個數字,在今年顯示爲一個字符串
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filterBy'
})
export class FilterByPipe implements PipeTransform {
transform(value, args) {
if (!args[0]) {
return value;
} else if (value) {
return value.filter(item => {
// tslint:disable-next-line:prefer-const
for (let key in item) {
if ((typeof item[key] === 'number' || item[key] instanceof Number) &&
(item[key].indexOf(args[0]) !== -1)) {
return true;
}
}
});
}
}
}
這不行嗎? – Amit
與預期不符。我剛剛意識到管道正在評估字符串而不是數字。 car_category應該只包含數字。 –