【发布时间】:2016-07-28 16:14:15
【问题描述】:
如何显示下面 Hero 对象的 ID 和标题? 下面的 Hero 接口是根据 Firebase JSON 响应映射的。
hero.component.ts
import {Component, Input} from 'angular2/core';
import {Hero} from '../model/hero';
@Component({
selector: 'hero-component',
template: `
{{hero | json }} this works. This display the Firebase JSON response as seen below
<br>
{{ Object.keys(hero)[0] }} this DOESN'T work
<br>
{{ hero[Object.keys(hero)[0]].title }}this also DOESN'T work
`
})
export class HeroComponent {
@Input()
hero:Hero;
}
hero.ts
export interface Hero {
[id: string]: {
createdAt: number;
isActive: boolean;
title: string;
updatedAt: number;
}
}
Firebase JSON 响应
{ "-KEMOfA5KFK98AXNhPY0": { "createdAt": 1459607745222, "isActive": true, "title": "Wind Hero", "updatedAt": 1459607745222 } }
【问题讨论】:
-
有一点需要注意,我没有使用 AngularFire2。我正在使用 Firebase REST API。我很难将 Angular2 与 Firebase REST API 一起使用,因为我不知道如何将 Firebase JSON 响应映射到 Typescript 接口以及如何访问变量。如果我使用 AngularFire2 会更容易吗?
-
为什么不使用服务中的 Firebase,并让服务转换响应并以更可用的格式返回?这会将控制器和视图代码与这些 firebase 问题隔离开来。
-
好主意。我对 Angular2 和 Firebase 不是很熟悉。所以我现在能做的就是关注我找到的任何截屏视频。 @JB Nizet 你会怎么做?你有这个建议的 Github repo 吗?
-
没有。我从未使用过 Firebase。但是你会做一些类似于in the doc 描述的使用 Http 的事情(在服务中,发出你的请求,并将响应数据转换为 JSON),除了这里,服务将调用 firebase,并将返回的 firebase 数组转换为一个更有用的对象。
标签: json typescript firebase angular