Jek Jek - 2 years ago 153
JSON Question

Reading JSON using Typescript in Angular2

After doing a POST to Firebase, I have this returned from Firebase

{ "name": "-KBfn7iFNIxSuCL9B-g5" }

  1. How do I use Typescript to read the response returned from the POST request? Only the value
    is need for routing. My existing incomplete code looks like this:

addHeroGotoHeroDetail() {
let heroId: string;
.subscribe(response => {
//do something to make the heroId = -KBfn7iFNIxSuCL9B-g5
this._router.navigate(['hero-detail', {id: heroId}]);

The goal is to have a button in the homepage where user can click on it to create a new hero Id in Firebase then redirect it to the newly created hero detail page, where he can do more detail updating.

Also after doing a GET from Firebase, I have this returned from Firebase

{ "-KBfn-cw7wpfxfGqbAs8": { "created": 1456728705596, "hero": "Hero 1", "...": "..."} }

  1. Should I create an interface for the hero JSON returned by Firebase?

  2. If yes for question 2, how should the interface look?

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. If yes for question 2, how do I use Typescript to parse the JSON object to the interface? Code sample would be very much appreciated.

The goal is to display the hero detail to the user, and allow the user to add more details to the hero such as Date of Birth, Gender and etc... and then update Firebase with these changes.

Answer Source

1. See below.

2. Yes, you should create an interface that matches the return type from Firebase.

3. Based on your example JSON, this is how I would structure the return type's interface:

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

4. To parse the response from Firebase into a strongly-typed TypeScript object, do something like this:

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

You can then return only the ID, if you wish, by doing something like this:

// 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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download