我已经仔细研究过这个但是找不到有效的答案。
当subscribe()方法成功返回'联系人时,我试图为附加功能实现回调$'可观察,但在订阅上使用complete()不会做任何事情。
我也试过在其他地方建议使用finally()on observable,但这也不起作用。
使用complete():
ngOnInit() {
this.getContacts()
.finally(() => console.log('a'))
.subscribe(
data => {
this.contacts = data;
console.log('NewInvoice.contacts:', data);
this.selectedContactId = this.contacts[0].id;
console.log('selectedContactId: ' + this.selectedContactId);
},
error => {
console.error('Error getting contacts via subscribe() method:', error);
},
() => {
this.getSelectedContact();
}
)
}
使用finally():
getSelectedContact() {
this.contactsCollection.doc(this.selectedContactId).ref.get().then(snapshot => {
this.selectedContact = snapshot.data() as Contact;
console.log('selectedContact:', this.selectedContact);
})
}
可观察完成时回调的方法:
{{1}}
答案 0 :(得分:0)
没有更多信息很难说,但我会给出一个镜头:
ngOnInit() {
this.getContacts()
.subscribe(
data => {
this.contacts = data;
console.log('NewInvoice.contacts:', data);
this.selectedContactId = this.contacts[0].id;
console.log('selectedContactId: ' + this.selectedContactId);
},
error => {
console.error('Error getting contacts via subscribe() method:', error);
},
() => {
this.getSelectedContact()
.asObservable()
.subscribe((a) => console.log(a));
}
)
}
并且:
getSelectedContact() {
return this.contactsCollection.doc(this.selectedContactId).ref.get().then(snapshot => {
this.selectedContact = snapshot.data() as Contact;
console.log('selectedContact:', this.selectedContact);
})
}
或者更清洁一点:
const callback = (a) => console.log(a);
...
() => {
this.getSelectedContact(callback);
}
...
getSelectedContact(callback) {
this.contactsCollection.doc(this.selectedContactId).ref.get()
.then(snapshot => {
this.selectedContact = snapshot.data() as Contact;
console.log('selectedContact:', this.selectedContact);
})
.then(a => callback(a));
}
最后@Picci建议:
this.getContacts()
.last()
.exhaustMap((data) => this.getSelectedContact(data))
.map(a => console.log(a))
.subscribe();
请注意,以上所有代码均未经过测试,仅供参考。