[英]How to resolve Promise mismatch in Angular / Typescript app?
I am trying to retrieve a User
object from Firestore in my Angular app.我正在尝试在我的 Angular 应用程序中从 Firestore 检索User
object。
User
model: User
model:
import { PlaceLocation } from './location.model';
export class User {
constructor(
public userId: string,
public userName: string,
public isMechanic: boolean,
public location: PlaceLocation
) { }
}
Component:零件:
user: User;
this.usersService
.getUserByUserId(paramMap.get('id'))
.subscribe(user => {
this.user = user;
});
Users Service:用户服务:
getUserByUserId(userId: string) {
return of(
firebase.firestore().collection("users").where("userId", "==", userId)
.get()
.then((querySnapshot) => {
console.log("Query Snapshot:", querySnapshot);
}).catch((err) => {
console.log("Query Error:", err);
})
);
}
But I'm getting this compilation error when I try to assign this.user = user
:但是当我尝试分配this.user = user
时出现此编译错误:
Type 'Promise' is missing the following properties from type 'User': userId, userName, isMechanic, location “Promise”类型缺少“用户”类型的以下属性:userId、userName、isMechanic、位置
Can someone please tell me what changes are required to resolve this issue?有人可以告诉我解决此问题需要进行哪些更改吗?
you're returning an observable of a promise... think you want from
, which converts a promise into an observable.您正在返回 promise 的 observable... 认为您想要from
,它将 promise 转换为 observable。
getUserByUserId(userId: string) {
return from(
firebase.firestore().collection("users").where("userId", "==", userId)
.get()
).pipe(
map(querySnapshot => { ... do transform ... }),
tap( // handle errors / logging in observable fashion
query => console.log(query, 'success),
error => console.log(error, 'error')
),
// catchError(error => { ... do something with error ... })
);
}
"from(...promise...)" solution will not always work. “来自(...promise...)”解决方案并不总是有效。 Promise could resolve before you soubscribe on. Promise 可以在您订阅之前解决。
True way is make observable at first:真正的方法是首先让可观察:
getUserByUserId(userId: string) {
return new Observable<any>((observer: Observer<any>) => {
firebase.firestore().collection("users").where("userId", "==", userId)
.get()
.then((querySnapshot) => {
observer.next(querySnapshot);
observer.complete();
}).catch((err) => {
observer.error(err);
})
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.