简体   繁体   中英

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

你必须施展它:

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

You'll need to convert the data to JSON. Try using data.json as demonstrated below.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM