Angular2 cast a json result to an interface

后端 未结 2 920
不知归路
不知归路 2020-12-15 17:53

Using Angular2 and typescript, I have JSON returned from a webApi and I need to get it into an array of a certain type. I can\'t figure out how to cast the json to the inte

2条回答
  •  伪装坚强ぢ
    2020-12-15 18:27

    You can do a type assertion to the interface you are expecting on the object created by JSON.parse.

     this.http.get('http://localhost:4200/').subscribe((value: Response) => {
        let hero = value.json();
      });
    

    However this will not result in any errors if the server sends you bad objects because of 2 reasons.

    At compile time the transpiler does not know what the server will send.

    At runtime all type information is erased since everything gets compiled to javascript.

提交回复
热议问题