Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write interface for the response for angular's must httpclient

I am trying to fetch the data from api using the angular's new httpclient, I get the error property doesnt exist on type IMessage[]. How do i write an interface for the following response,

{"data":{"Messages":[{"Id":28,"MessageContent":"test data tsn","FromUserId":"74df8f98-2925-4242-8d32-8b09f3691396","UserName":"[email protected]","ToUserId":"96b1c943-ade0-4026-b8ed-0f4a6231e586","ProductId":null,"ParentMessageId":null,"Subject":"Test Message by Dev Team","StyleNumber":null}],"Pagination":{"Page":1,"PageLength":20,"TotalRecords":20,"TotalPages":1},"MessageLimit":{"TotalMessageCount":5,"RemainingMessageCount":3}}}

What i tried here,

export interface IMessage {
    data: {
        Messages: Messages[];
    };
}

interface Messages {
    id: number;
    messageContent: string;
    fromUserId: string;
    toUserId: string;
    productId?: number;
    parentMessageId?: number;
    subject: string;
    styleNumber?: string;
}

My code on stackblitz

enter image description here

// Here is the code
    import { Component, Input, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { IMessage } from './message.interface';
import { HttpClient, HttpResponse, HttpParams, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements OnInit  {
  constructor (private http: HttpClient) {
        console.log('Message repository service instance');
    }
        readonly ROOT_URL = '//52.70.78.117:7111/api/message';
ngOnInit() {
    this.getAllMessages();
  }
  @Input() name: string;
  messages;
  getAllMessages(): Observable<IMessage[]> {
    this.getAllMessagesFromApi()
    .subscribe(data => {
      console.log('data is =>', data.data);
      this.messages = data;
    },
    err => {
      console.log('Error occured while fetching message List');
    });
    return;
  }
  getAllMessagesFromApi(): Observable<IMessage[]> {
      return this.http.get<IMessage[]>(`${this.ROOT_URL}/list`);
  }
}
like image 799
Karty Avatar asked Aug 03 '26 09:08

Karty


1 Answers

You should change what type your getAllMessagesFromAPI() method returns to IMessage

// method returns type IMessage
getAllMessagesFromApi(): Observable<IMessage> { 
    // http request returns type IMessage
    return this.http.get<IMessage>(`${this.ROOT_URL}/list`); 
}

Now you can access your array of messages

.subscribe(data => {
    this.messages = data.data.Messages;
},
like image 83
LLai Avatar answered Aug 06 '26 05:08

LLai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!