下面是我导航到Angular应用程序的Conversation-List
页时执行的代码:
ngOnInit() {
this.authSub = this.authService.userId.pipe(take(1)).subscribe(userId => {
console.log('NG ONINIT');
this.conversationsSub = this.conversationsService.conversations.subscribe(conversations => {
loadingEl.dismiss();
this.loadedConversations = conversations.filter(
conversation =>
conversation.userId === userId || conversation.mechanicId === userId
);
console.log('Loaded Conversations:', this.loadedConversations);
})
});
}
ionViewWillEnter() {
console.log('ION VIEW WILL ENTER');
this.conversationsService.fetchConversations().subscribe();
}
当我最初导航至此页面时,User
详细信息显示在控制台中:
但是,当我刷新页面时,User
是空的:
有人可以告诉我为什么刷新页面时用户未定义吗?
此User
对象用于下面的Conversation-list
:
Conversation-list.page.html
:
<ion-item *ngFor="let conversation of loadedConversations">
<app-conversation-item [conversation]="conversation"></app-conversation-item>
</ion-item>
打字稿:
export class ConversationItemComponent {
@Input() conversation: Conversation;
ngOnInit() {
this.usersSub = this.usersService.getUserByUserId(this.conversation.mechanicId).subscribe(
user => {
console.log(`User`, user);
console.log(`Username`, user.name);
console.log(`Image URL`, user.imageUrl);
this.username = user.name;
this.imageUrl = user.imageUrl;
}
);
}
}
答案 0 :(得分:0)
有2点可以改进:
1-不要使用嵌套订阅,因为这不是RxJS的最佳实践。您可以使用例如combineLatest
:
ngOnInit() {
combineLatest([this.authService.userId, this.conversationsService.fetchConversations()])
.pipe(takeUntil(this.destroy$))
.subscribe(([userId, loadedConversations]) => {
console.log('UserId', userId);
this.loadedConversations = loadedConversations.filter(
conversation =>
conversation.userId === userId || conversation.mechanicId === userId
);
console.log('Loaded Conversations', this.loadedConversations);
}
}
// ionViewWillEnter() has been removed, as we embed the call in combineLatest
combineLatest
运算符期望两个可观测值都发出一个值。否则,如果您只想获取两个可观察值之一的最新值(例如Auth Service),则可以使用withLatestFrom()
运算符。
2-如果代码在组件中,则应记住退订可观察对象,以避免引入内存泄漏。例如,您可以使用takeUntil(this.destroy$)
运算符和在onDestroy组件挂钩中调用的主题:
private destroy$ = new Subject<boolean>();
ngOnDestroy() {
this.destroy$.next(true);
}