0

AngularのHttpclientModuleを使ってExpressからデータを取得して表示する処理を実装しています。
GETで受け取り値を表示する際に以下のエラーが出ます。
このエラーを解消するにはどうすればいいでしょうか?

Property 'id' does not exist on type 'number | Comment | (() => string) | (() => string) | (() => Comment | undefined) | ((...items: Comment[]) => number) | { (...items: ConcatArray<Comment>[]): Comment[]; (...items: (Comment | ConcatArray<...>)[]): Comment[]; } | ... 27 more ... | (() => { ...; })'.
  Property 'id' does not exist on type 'number'.

9                 <h4 class="media-heading">{{ comment.value.id | json }}</h4>

・該当のコード
型定義

export interface Comment{
  
  comments: [
    {
      id: number,
      message: string,
      }
    ]
}

comment.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { catchError } from "rxjs/operators";
import { Observable } from 'rxjs';
import { Comment } from '../models/comment';
import { of } from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class CommentService {
  private base_url: string = 'http://localhost:3000'
  comments!: Comment

  constructor(private http: HttpClient) { }

  getComments(): Observable<Comment>{
    return this.http.get<Comment>(`${this.base_url}/comments`) // get通信
    .pipe(
      catchError(this.handleError<Comment>('getComments'))
    );
  }

  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      // TODO: リモート上のロギング基盤にエラーを送信する
      console.error(error); // かわりにconsoleに出力
      // 空の結果を返して、アプリを持続可能にする
      return of(result as T);
    };
  }
  

}

app.commponet.ts
ngOnInit()内の返す値の型がおかしいのかなと予想します

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { ApiService, Item} from './service/api.service';
import { Comment } from './models/comment';
import { CommentService } from './service/comment.service'
// import { Comment } from './class/comment'
import { NgForm } from '@angular/forms';

@Component({
  selector: 'ac-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'web-app';
  
  comes!: Comment[]
  // public comments$!: Observable<Comment>
  form!: NgForm


  constructor(private api:ApiService, private comment: CommentService){}

  ngOnInit(): any{
    this.comment.getComments().subscribe((res: any) => {
       this.comes = res.comments
       console.log(this.comes)
    })
    
  }
}

app.component.html

<div *ngFor="let comment of comes | keyvalue">
        
          <div class="media">
            <div class="media-body">
              <div class="d-flex w-100 justify-content-between">
                <h4 class="media-heading">{{ comment.value.message | json }}</h4>
                <small class="media-date">{{ comment | json}}</small>
              </div>
            </div>
 </div>

comment | jsonの中身

{ "id": 1, "message": "おはようございます", "createdAt": "2022-02-17T23:47:57.011Z", "updatedAt": "2022-02-22T03:45:49.555Z" }

・追記
エラー全文

Property 'message' does not exist on type 'KeyValue<string, number | Comment | (() => string) | (() => string) | (() => Comment | undefined) | ((...items: Comment[]) => number) | { (...items: ConcatArray<Comment>[]): Comment[]; (...items: (Comment | ConcatArray<...>)[]): Comment[]; } | ... 27 more ... | (() => { ...; })>'.

comment | jsonの中身が{ "key": "0", "value": { "id": 1, "message": "おはようございます", "createdAt": "2022-03-06T10:01:29.781Z", "updatedAt": "2022-03-06T10:01:29.790Z" } }
なので、{{comment.value.message}}で表示しようとすると以下のエラー

Property 'message' does not exist on type 'number | Comment | (() => string) | (() => string) | (() => Comment | undefined)

・修正箇所

export class CommentService {
  private base_url: string = 'http://localhost:3000'
  comments!: ResponseComment

  constructor(private http: HttpClient) { }

  getComments(): Observable<ResponseComment>{
    return this.http.get<ResponseComment>(`${this.base_url}/comments`)
    .pipe(
      catchError(this.handleError<ResponseComment>('getComments'))
    );
  }

・型定義

export interface Comment {  
  id: number
  message: string
  createdAt: number
  user_id: number
}

export interface ResponseComment {  
  comments: Array<Comment>
}

1 件の回答 1

0

app.commponet.tscomesComment[] の型だと宣言しているので以下のようなCommentの配列を期待するようになっています

comes = [
{
  comments: [
    {
      id: number,
      message: string,
      }
    ]
},
{
  comments: [
    {
      id: number,
      message: string,
    }
  ]
}
]

実際は { id: number, message: string } 配列を期待されているようなのでAPIレスポンスとモデルでインターフェイスを分けたほうが良いでしょう

export interface Comment {  
  id: number
  value: {
    message: string
  }
}

export interface ResponseComment {  
  comments: Array<Comment>
}

インターフェイス変更後、CommentServiceの型を変更します。(他にも細かい修正が発生するかもしれません)

// comment.service.ts
export class CommentService {
// 省略
  getComments(): Observable<ResponseComment>{
    return this.http.get<ResponseComment>(`${this.base_url}/comments`)
    .pipe(
      catchError(this.handleError<ResponseComment>('getComments'))
    );
  }
// 省略
}
<div *ngFor="let comment of comes | keyvalue">
        
          <div class="media">
            <div class="media-body">
              <div class="d-flex w-100 justify-content-between">
                <h4 class="media-heading">{{ comment.value.message }}</h4>
                <small class="media-date">{{ comment | json}}</small>
              </div>
            </div>
 </div>
2
  • 回答ありがとうございます。 レスポンスとモデルで型定義を分けて、comment.service.ts等も編集いたしました。 しかし、{{comment.message}}で中身を表示すると、**Property 'message' does not exist on type 'KeyValue<string, number | Comment | (() => string) | (() => string) | (() => Comment | undefined) | ((...items: Comment[]) => number) ** というエラーが表示されます。
    – Tikka
    2022年3月7日 22:40
  • comment | json の結果が想定と違ったのでCommentインターフェイスと合わせてビュー側を {{ comment.value.message }} に変更しました
    – sugumura
    2022年3月8日 2:44

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。