我正在尝试从API检索数据,然后按ISO日期排序。在我的组件ngOnInit()
中:
messages: Message[] = [];
ngOnInit() {
this.getAccounts(); // populates accounts as well as messages
this.sortMessages(this.messages);
}
在我的API调用中填充messages
数组:
getAccounts() {
var myMessages = this.messages; // pass by reference
this.apiService.getAccounts().subscribe(
res => this.accounts = res.Items,
err => console.log(err),
() => this.accounts.forEach(function(acc) {
if(acc.messages) {
acc.messages.forEach(function(message) {
myMessages.push(message);
});
}
}));
}
尝试排序:
sortMessages(messages) {
messages.sort(function(a, b) {
return (a.date < b.date) ? -1 : ((a.date > b.date) ? 1 : 0);
});
console.log('sorted: ', messages);
}
预期:
message
[1]
应该在最后,因为它有最新的ISO日期。但是,我的数组根本没有排序。这是否与异步和ngOnInit()
中调用的这些方法有关?或者我错过了一些简单的东西?
答案 0 :(得分:0)
您没有得到预期的结果,因为当您调用sortMessage时,您的messages数组为空。
解决方案1:
async ngOnInit() {
await this.getAccounts(); // populates accounts as well as messages
this.sortMessages(this.messages);
}
解决方案2:
ngOnInit() {
this.getAccounts(); // populates accounts as well as messages
}
getAccounts() {
var myMessages = this.messages; // pass by reference
this.apiService.getAccounts().subscribe(
res => this.accounts = res.Items,
err => console.log(err),
() => {
this.accounts.forEach(function(acc) {
if(acc.messages) {
acc.messages.forEach(function(message) {
myMessages.push(message);
});
}
}
this.messages.sort(function(a, b) {
return (a.date < b.date) ? -1 : ((a.date > b.date) ? 1 : 0);
});
console.log('sorted: ', messages);
}
);
}
答案 1 :(得分:0)
我通过将消息推送到订阅的成功部分并将排序调用放入完成部分来解决这个问题:
getAccounts() {
var myMessages = this.messages; // pass by reference
this.apiService.getAccounts().subscribe(
res => {
this.accounts = res.Items,
this.accounts.forEach(function(acc) {
if(acc.messages) {
acc.messages.forEach(function(message) {
myMessages.push(message);
});
}
});
}
err => console.log(err),
() => this.sortMessages(myMessages));
}