パイプはname
プロパティでオブジェクトの配列をソートしなければなりません。カスタムパイプがAngular2で正しく機能しない
ソートby.pipe.ts:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sortBy'
})
export class SortByPipe implements PipeTransform {
private name: string;
transform(array: Array<any>, args: string[]): Array<any> {
array.sort((a: any, b: any) => {
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
} else {
return 0;
}
});
return array;
}
}
app.component.html:
<table>
<tr *ngFor="let elem of _values | sortBy">
<td>{{ elem.name }}</td>
<td>{{ elem.ts }}</td>
<td>{{ elem.value }}</td>
</tr>
</table>
app.module.ts:
//other imports
import { SortByPipe } from './sort-by.pipe';
@NgModule({
declarations: [
SortByPipe
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: []
})
export class AppModule { }
オブジェクトの配列:
[{
"name": "t10",
"ts": 1476778297100,
"value": "32.339264",
"xid": "DP_049908"
}, {
"name": "t17",
"ts": 1476778341100,
"value": "true",
"xid": "DP_693259"
}, {
"name": "t16",
"ts": 1476778341100,
"value": "true",
"xid": "DP_891890"
}];
それは適切にオブジェクトをソートしませんが、また、すべてのエラーをスローしません。
おそらくファイルに問題がありますか?
たぶん、あなたが望むものを比較整数を行うことですされている場合角度は気にしないように、これはそれを作る。これを読んでhttp://stackoverflow.com/questions/5630123/javascript-string-integer-comparisons –
あなたは '' t10 '、' t16 '、' t17''の注文を期待していますか? – ps2goat
@ ps2goatはい私の友人 –