我正在与 rxjs 作斗争。我想对来 self 的订阅的数组进行排序。 但那种从来不玩的.. 所以首先我尝试从服务中显示 userBirthdayDate 但没有按预期工作。
这是我的服务
getAllUsers() {
return new Promise((resolve, reject) => {
firebase
.database()
.ref()
.child('users')
.on(
'value',
snapshot => {
resolve(
snapshot.forEach(childSnapshot => {
this.usersBirthday = childSnapshot.val()
? childSnapshot.val()
: [];
this.emitBirthday();
})
);
},
error => {
reject(error);
}
);
});
}
我的组件.ts
export class WidgetBirthdayComponent implements OnInit {
users: User[];
usersBirthdayDate = [];
usersSubscription: Subscription;
constructor(private userService: UsersService) {}
ngOnInit() {
// this.usersSubscription = this.userService.birthdaySubject.subscribe(
// test => {
// this.usersBirthdayDate.push(test);
// }
// );
// this.userService.emitBirthday();
// this.userService.getAllUsers();
const myArray = [
{
name: "Joel",
birthdayDate: "Wednesday, November 25, 1992"
},
{
name: "Sarah",
birthdayDate: "Thursday, April 16, 1992"
},
{
name: "Beverly",
birthdayDate: "Thursday, February 26, 1998"
}
];
myArray.sort(function compare(a, b) {
const now = new Date();
const dateA = new Date(a.birthdayDate);
dateA.setFullYear(now.getFullYear());
if (dateA.getTime() - now.getTime() < 0) {
dateA.setFullYear(now.getFullYear() + 1);
}
const dateB = new Date(b.birthdayDate);
dateA.setFullYear(new Date().getFullYear());
dateA.setFullYear(now.getFullYear());
if (dateB.getTime() - now.getTime() < 0) {
dateB.setFullYear(now.getFullYear() + 1);
}
return dateA.getTime() - dateB.getTime();
});
console.log(myArray);
}
所以我尝试使用强大的数据,并且我的函数排序运行良好..但我无法在其上使用 usersBirthdayDate[] ..请需要帮助:)
最佳答案
如果您尝试在订阅之外对数组进行排序(例如在您的代码片段中),它将不起作用,因为当您的代码运行时,您只在 ngOnInit Hook 中对数组进行一次排序。到那时,您的可观察对象尚未发出任何 userBirthday。因此 usersBirthdayDate
数组为空。
我不确定您在何时何地试图让排序发生,但您是否尝试过类似以下的操作:
this.usersSubscription = this.userService.birthdaySubject.subscribe(
test => {
this.usersBirthdayDate.push(test);
this.usersBirthdayDate.sort(yourSortingFunction);
}
);
如果这不起作用,也许您可以多解释一下当您收到新用户时您的订阅会发生什么?然后,如果需要,我就可以编辑我的答案。
关于javascript - 从 firebase 快照订阅后显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60304421/