我正在从事 ionic 2 项目。我能够返回设备/手机中的所有联系人。但我使用的 promise 代码由于一次只有一个请求而性能非常慢。现在,我想将该 promise 代码更改为可观察的代码。请帮我解决这个问题。
findContact(searchKey){
if(searchKey.target.value == "" || searchKey.target.value == undefined || searchKey.target.value == null){
this.contactSelected = false;
} else{
this.contactSelected = true;
}
let options = {
multiple: true,
hasPhoneNumber: true,
filter: searchKey.target.value
}
let cantactFields = ['displayName', 'phoneNumbers'];
Contacts.find(cantactFields, options).then(res => {
this.contactResults = res;
}, (er) => {
console.log(er);
})
}
Contacts.find()
是我使用 promise 的方法。而且这个方法返回联系人的速度非常慢。
最佳答案
您可以使用 Observable.fromPromise
将您的 Promise 包装在 observable 中。
类似这样的事情可以将你的 promise 包装在可观察中。
findContact(searchKey){
if(searchKey.target.value == "" || searchKey.target.value == undefined || searchKey.target.value == null){
this.contactSelected = false;
} else{
this.contactSelected = true;
}
let options = {
multiple: true,
hasPhoneNumber: true,
filter: searchKey.target.value
}
let cantactFields = ['displayName', 'phoneNumbers'];
var promise =Contacts.find(cantactFields, options).then(res => {
this.contactResults = res;
}, (er) => {
console.log(er);
})
return PromiseObservable.create(promise); // Observable.fromPromise(promise)
}
希望这有帮助
关于angular - 如何将 Promise 转换为 Observable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40713514/