LoginSignup
11
6

More than 5 years have passed since last update.

JSONを受ける - Angular 6 メモ

Last updated at Posted at 2018-07-17

コレは何?

Angular&TypeScript初心者が、@angular/common/httpを使ってレスポンスをJSONで受け取る部分でのコンパイルエラーに「えっ?型のエラー?どうするの?」と四苦八苦したときの解決メモです。(解決方法が正しくなかったらご指摘いただけると幸いです)

エラーの内容

ERROR in src/app/hoge/hoge.component.ts(xx,yy): error TS2339: Property 'data' does not exist on type 'Object'.

dataと指定しているけど、そのObjectにはdataというプロパティ(属性、要素)は存在してないよ。」という内容。意訳すると「(あるかもしれないけど)dataってプロパティがあるよ、って指定されてないObjectよね」っていう指摘です。

ちなみに、エラー時のhogehoge()はこうなっています。これを解決する修正方法を以下に2つ書きます。

hoge.component.tsのhogehoge()を抜粋
  hogehoge() {
    this.http.get('/api/hogehoge').subscribe( res => {
      let response = res;
      this.test_data = response.data;  // <<<<< ココでエラー発生 <<<<<
    }, err => {
      if(err.status === 401) {
          this.router.navigate(['login']);
      }
    });
  }

エラーを修正したコード

シナリオ:「APIエンドポイントの/api/hogehogeからデータ(JSON)を取得、取得データの要素datatest_dataにセットする」

anyを使う

その名の通りでanyは「何でもOK型」です。せっかくのTypeScriptなn....(ry。
実装時は最も速く簡単な指定方法です。

hoge.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
.
.
@Component({
.
.
})
export class HogeComponent implements OnInit {

  private test_data: String[];

  constructor(private http: HttpClient) { }

  ngOnInit() { }

  hogehoge() {
    this.http.get('/api/hogehoge').subscribe( res => {
      let response:any = res;  // <<<<< 違いはココ <<<<<
      this.test_data = response.data;
    }, err => {
      if(err.status === 401) {
          this.router.navigate(['login']);
      }
    });
  }

}

Interfaceを使う

APIからのレスポンスが固定されている場合は恩恵を受けやすい。「あれっ、ここってどんな形でレスポンス返ってくるんだっけ?」というのも起きづらくなるでしょう。

hoge.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
.
.
interface ResJSON {
    success: boolean;  // <<<<< 区切りはコンマ(,)ではなくセミコロン(;) <<<<<
    data: any;  // <<<<< 区切りはコンマ(,)ではなくセミコロン(;) <<<<<
}
.
.
@Component({
.
.
})

export class HogeComponent implements OnInit {

  private test_data: String[];

  constructor(private http: HttpClient) { }

  ngOnInit() { }

  hogehoge() {
    this.http.get('/api/hogehoge').subscribe( res => {
      let response = <ResJSON>res;  // <<<<< 違いはココ <<<<<
        this.test_data = response.data;
      }, err => {
        if(err.status === 401) {
          this.router.navigate(['login']);
      }
    });
  }

}

参考

お礼

@takustaqu さん、ありがとうございました!

11
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
6