【问题标题】:Reading JSON using Typescript in Angular2在 Angular2 中使用 Typescript 读取 JSON
【发布时间】:2016-06-12 03:47:42
【问题描述】:

在对 Firebase 进行 POST 之后,我从 Firebase 返回了这个

{ "name": "-KBfn7iFNIxSuCL9B-g5" } 
  1. 如何使用 Typescript 读取 POST 请求返回的响应?路由只需要值-KBfn7iFNIxSuCL9B-g5。我现有的不完整代码如下所示:
   addHeroGotoHeroDetail() {
     let heroId: string;
     this._firebaseService.postHero()
        .subscribe(response => {
          //do something to make the heroId = -KBfn7iFNIxSuCL9B-g5 
     });
     this._router.navigate(['hero-detail', {id: heroId}]);
   }

我们的目标是在主页上有一个按钮,用户可以点击它在 Firebase 中创建一个新的英雄 ID,然后将其重定向到新创建的英雄详细信息页面,在那里他可以进行更多详细信息更新。


在从 Firebase 执行 GET 之后,我也从 Firebase 返回了这个

{ "-KBfn-cw7wpfxfGqbAs8": { "created": 1456728705596, "hero": "Hero 1", "...": "..."} }
  1. 我应该为 Firebase 返回的英雄 JSON 创建一个接口吗?

  2. 如果问题 2 为“是”,界面应该如何?

export interface X {
  id: string; //id defined by Firebase e.g. -KBfn-cw7wpfxfGqbAs8 
  hero: string; //name of the hero e.g. Hero 1 
  created: number; // The time when the hero was created
}
  1. 如果问题 2 是,如何使用 Typescript 将 JSON 对象解析到接口?非常感谢代码示例。

目标是向用户显示英雄详细信息,并允许用户向英雄添加更多详细信息,例如出生日期、性别等……然后使用这些更改更新 Firebase。

【问题讨论】:

    标签: json typescript firebase angular


    【解决方案1】:

    1.见下文。

    2.是的,您应该创建一个与 Firebase 的返回类型匹配的接口。

    3. 根据您的 JSON 示例,我将采用以下方式构建返回类型的接口:

    export interface FirebaseResponse {
        [id: string]: {
            created: number;
            hero: string;
        }
    }
    

    4. 要将 Firebase 的响应解析为强类型 TypeScript 对象,请执行以下操作:

    let firebaseResponse = <FirebaseResponse>JSON.parse(response);
    

    然后,如果您愿意,您可以通过执行以下操作仅返回 ID:

    // note: this is making some assumptions about your response type.
    // You may need a more sophisticated way of returning the ID depending
    // on the structure of the response - for example, if the object has
    // more than one key.
    return Object.keys(firebaseResponse)[0];
    

    【讨论】:

    • 感谢内森朋友。这看起来很有希望。我会试试这个解决方案。
    • 还有一个网站可以让我阅读像您的解决方案这样的领域吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 2023-04-03
    • 2022-01-22
    • 2016-11-03
    • 2020-03-21
    相关资源
    最近更新 更多