Search code examples
jsonangulartypescriptangular-httpclient

Argument of type 'Object' is not assignable to parameter of type 'JSON' Httpclient GET


Hello i am working on an Angular 6 + Flask application and I have this issue:

error TS2345: Argument of type 'Object' is not assignable to parameter of type 'JSON'.

when my code does that :

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MessageService } from '../shared/message.service';

@Component({
  selector: 'app-network-monitorer',
  templateUrl: './network-monitorer.component.html',
  styleUrls: ['./network-monitorer.component.css']
})
export class NetworkMonitorerComponent implements OnInit {

  mqttMessageData : JSON[]=[];
  coapMessageData : JSON[]=[];
  xmppMessageData : JSON[]=[];

  constructor(private httpClient: HttpClient, private messageService:MessageService) { }

  ngOnInit() {
    setInterval(()=>{
      this.getMqttMessages(); },2000);
  }

  getMqttMessages() {
    this.httpClient.get('http://127.0.0.1:5002/messages/mqtt').subscribe(data => {
      this.mqttMessageData.push(data);
      console.log("message :")
      console.log(this.mqttMessageData.length())
      console.log(data);
    });
  }

So basically when the component is loading i make a request to my python server to fetch some data which are returned to the client in JSON, but angular seems to think that 'data' is type of Object so i can't add it to my list of JSON


Solution

  • You'll have to cast it:

    this.httpClient.get<JSON[]>('http://127.0.0.1:5002/messages/mqtt').subscribe(data => {