我正试图在我的Angular应用程序中从Firestore检索一个User
对象。
User
型号:
import { PlaceLocation } from './location.model';
export class User {
constructor(
public userId: string,
public userName: string,
public isMechanic: boolean,
public location: PlaceLocation
) { }
}
组件:
user: User;
this.usersService
.getUserByUserId(paramMap.get('id'))
.subscribe(user => {
this.user = user;
});
用户服务:
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);
})
);
}
但当我尝试分配this.user = user
:时,我遇到了这个编译错误
类型"Promise"在类型中缺少以下属性"用户":userId,用户名,isMechanic,位置
有人能告诉我解决这个问题需要做哪些更改吗?
您正在返回一个可观察到的承诺。。。认为您想要from
,它将承诺转换为可观察的。
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…("解决方案并不总是有效的。承诺可以在你订阅之前解决。
真正的方法是首先使其可观察:
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);
})
});
}