2016-02-29 83 views
0

做一个POST到火力地堡后,我这个从火力地堡阅读使用JSON在打字稿Angular2

{ "name": "-KBfn7iFNIxSuCL9B-g5" } 
  1. 如何使用打字稿回读从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}]); 
    } 

我们的目标是在主页按钮,其中用户可以在其上单击创建在火力地堡一个新的英雄ID,然后在它重定向到新创建英雄详情页面,在那里他可以做更多细节更新。


也做得从火力地堡一个GET后,我此从返回火力地堡

{ "-KBfn-cw7wpfxfGqbAs8": { "created": 1456728705596, "hero": "Hero 1", "...": "..."} } 
  • 我应该建立用于通过返回的英雄JSON的接口火力地堡?

  • 如果对于问题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 
    } 
    
  • 如果是对于问题2,要如何使用打字稿解析JSON对象到接口?代码示例将非常感谢。
  • 我们的目标是,以显示英雄的细节给用户,并允许用户如出生日期,性别和等日期的详细信息的英雄添加...,然后用这些变化更新火力地堡。

    回答

    1

    1.见下文。

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

    根据你的榜样JSON,这是我会怎样构建的返回类型的接口:

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

    4.为了解析从火力地堡的响应成一个强类型的打字稿对象,做这样的事情:

    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]; 
    
    +0

    谢谢Nathan Friend。这看起来有希望。我会尝试这个解决方案。 –

    +0

    也有一个网站,我喜欢你的解决方案在区域上阅读? –