[英]How to sort array of objects in my component with Angular 5?
在我說別的之前,我想說我對所有這一切都很陌生,所以盡量不要太技術化。 謝謝。 我有一個包含對象的數組。 每個對象都有一個日期,我正在嘗試按此日期對它們進行排序。
async list_all_shifts(){
try {
let response = (await this.shiftService.list_all_shifts().toPromise())
for (let shiftje of response) {
this.shiften.push(shiftje);
}
this.shiften.sort();
} catch (err) {
}
}
我遇到的問題是我嘗試對數組進行排序的部分實際上沒有做任何事情。 shiften 數組有許多帶有日期、beginHour、endHour 等的對象......在我的 html 組件中,它只是以隨機順序顯示日期,我希望它們排序。 我的 HTML 組件看起來像這樣;
<tr *ngFor="let shift of shiften, index as i;">
<td>{{shift.datum | date:'EEE, dd/MM/yyyy'}}</strong></td>
<td>{{ shift.beginuur }}h</td>
<td> {{ shift.einduur }}h </td>
<td>{{shift.helpers.ingeschreven.length}}/{{shift.helpers.max}}</td>
<td><button class="btn btn-success">Inschrijven {{ shift._id }}</button></td>
<td><button (click)="verwijderShift(shift, shift._id)">Verwijder</button></td>
</tr>
最后,我獲取數據的服務看起來像這樣(我正在使用帶有 api 的后端);
list_all_shifts(): Observable <any> {
const header = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': localStorage.getItem('token')
})
}
return this.http.get<any>(`${this.API_URL}/shifts`, header)
}
其中一些是荷蘭語,但我希望你明白我在這里想做的事情。 先感謝您。
像這樣做:
class Component {
shifts$: Observable<Shift>;
constructor(private shiftService: ShiftService) {
}
ngOnInit(){
this.shiftService.list_all_shifts()
.pipe(
map(shiftArray => [...shiftArray].sort()),
catchError(err => {
// handle the error
doSth()
// return an empty array so you template logic doesnt fail
return of([])
})
)
}
}
在您的模板中,使用異步管道:
<tr *ngFor="let shift of shifts$ | async, index as i;">
...
</tr>
從你凌亂的代碼我可以看出,你沒有使用好的 IDE。 考慮使用 IntelliJ 或 VScode 並注意你的代碼。 保持干凈和易於理解。
對於尋找相同答案的人。 正如評論中所寫的那樣,要獲得按日期排序的數組,您必須使用排序函數的第一個可選參數“compareFunction”。 請參閱https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
async list_all_shifts(){
try {
let response = (await this.shiftService.list_all_shifts().toPromise())
for (let shiftje of response) {
this.shiften.push(shiftje);
}
this.shiften.sort(function(a, b) {
return new Date(a.datum).getTime() - new Date(b.datum).getTime();
});
} catch(err) {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.