【发布时间】:2017-01-15 15:39:49
【问题描述】:
我的服务中有以下方法,它从 Firebase 返回一条与传入的 bugId 匹配的记录:
// 请注意,它位于 bugservice.ts 中
getBug(bugId: string): Promise<Bug> {
return this.bugsDbRef
.child(bugId)
.once('value')
.then(snapshot => {
const bugInfo = snapshot.val() as Bug;
bugInfo.id = snapshot.key;
}) as Promise<Bug>;
}
在我的 bugDetail 组件中,我将上述服务注入到我的 bugDetail 组件中,然后调用上述方法,如下所示:
export class BugDetailComponent implements OnInit, OnDestroy {
private subscription: Subscription;
private bugDetail: Bug = new Bug(null,null,null,null,null,null,null,null,null); // Trying to populate from Service Call i.e getBug
private bugId: string; // Come from URL
constructor(private bugService: BugService, private activatedRoute: ActivatedRoute) { }
ngOnInit() {
this.configureForm();
this.subscription = this.activatedRoute.params.subscribe(
(param: any) => {
this.bugId = param['id'];
});
const t = this.bugService.getBug(this.bugId);
console.log(t);
}
}
但是,当我使用 console.log 时,控制台中会显示以下内容:
当我删除 t 并将其替换为
this.bugDetail = this.bugService.getBug(this.bugId);
我得到的错误信息是:
类型“Promise”不可分配给类型“Bug”。 “Promise”类型中缺少属性“id”。
有人可以向我解释如何访问从 BugDetail 组件中的服务检索到的错误详细信息吗?
【问题讨论】:
-
这是预期的行为;您正在记录
Promise。要获得Bug,您需要调用this.bugService.getBug(this.bugId).then(bug => console.log(bug));此外,其他地方是您的代码,您可以调用new Bug(...)。如果Bug是一个类,您不能将snapshot.val()转换为Bug,因为它不是Bug实例。 -
好吧,现在我很困惑,在我的 getBug 方法中,我返回一个 Promise
,它告诉我我正在传回一个错误对象。在我的错误详细信息组件中,我调用此方法并对其进行扩展以适应您刚刚指定的附加 .then 函数。你能帮我看看 getBug 函数的代码和调用 getBug 的方法吗?我被这个承诺的东西弄糊涂了。
标签: angular typescript firebase firebase-realtime-database