我有一個名爲JobList的組件,它當前從文件中獲取JSON對象(稍後將成爲Web服務器)並顯示頁面上的作業列表。我希望列表按照Status.Order的每個作業中的屬性進行排序。Angular - 在添加數據後未對數組進行排序
要做到這一點,我正在使用一個管道,我已經在下面的代碼中設置。
問題:如果我不使用管道,作業將按文件順序顯示,但如果使用管道,則根本不會顯示任何內容。我在管道代碼中做錯了什麼?
如果我在管道代碼中的變換函數中添加一個console.log,那麼我可以看到一個空數組正在傳入。我希望在添加數據時看到第二個調用,但什麼也沒有。
export class JoblistComponent implements OnInit {
private openJobs = new Array();
private activeJobs = new Array();
constructor() { }
ngOnInit() {
const openJobs = this.openJobs;
const activeJobs = this.openJobs;
$.getJSON('assets/data/jobs.json', function (json: Array<any>) {
for (const job of json) {
if (job.Status.Section === 'Active') {
activeJobs.push(job);
} else {
openJobs.push(job);
}
}
});
}
}
爲了使我使用這個HTML內容。
<div class="job" *ngFor="let job of openJobs | orderByStatus" [ngStyle]="{ 'border-left-color': job.Group.Colour }">
<span class="title">12 Example Street, {{job.Location.Name}}</span>
<span>{{ job.Name }}</span>
<span>{{ job.Type.Name }}</span>
</div>
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'orderByStatus'
})
export class OrderByStatusPipe implements PipeTransform {
transform(array: Array<any>, args?: any): any {
array.sort((a: any, b: any) => {
if (a.Status.Order < b.Status.Order) {
return -1;
} else if (a.Status.Order > b.Status.Order) {
return 1;
} else {
return 0;
}
});
return array;
}
}
實施例工作
{
"_id": "597b5a700c1d413f20c4d67a",
"Name": "JOB-20170628-029",
"Created": "2017-07-28T15:38:24.619Z",
"Group": {
"_id": "5919e2f96b1822dc0daf94d5",
"Name": "Priority 3",
"Colour": "#1bb934",
"Order": 3,
"Class": "priority3"
},
"Type": {
"Name": "Type 2",
"_id": "597b5a680c1d413f20c4b5fc"
},
"Status": {
"Order": 2,
"Section": "Active"
}
"Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse sed lacus sit amet enim congue molestie. \nAenean pharetra tincidunt ligula a luctus. In vel interdum lacus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"Location": {
"Postcode": "RG31 6PL",
"Name": "RG31 6PL"
}
}
後,你有某種錯誤在你的Web控制檯?我在我應該工作的項目中實施了同樣的事情。雖然我能看到的唯一區別是我沒有使用'new Array()',而是使用通用的'[]' – masterpreenz