我环顾四周试图解决这个问题,但找不到有效的答案。
当 subscribe() 方法成功返回“contacts$”可观察对象时,我正在尝试为附加函数实现回调,但在订阅上使用 complete() 不会执行任何操作。
我也试过按照其他地方的建议在可观察对象上使用 finally(),但这也不起作用。
使用 complete():
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();
}
)
}
使用 finally():
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();
}
)
}
可观察完成的回调方法:
getSelectedContact() {
this.contactsCollection.doc(this.selectedContactId).ref.get().then(snapshot => {
this.selectedContact = snapshot.data() as Contact;
console.log('selectedContact:', this.selectedContact);
})
}
最佳答案
没有更多信息很难说,但我会试一试:
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();
请注意,以上所有代码均未经过绝对测试,仅供引用。
关于javascript - TypeScript/RxJS - 可观察的订阅()方法完成()未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49543040/