【问题标题】:Argument of type 'Object' is not assignable to parameter of type 'JSON' Httpclient GET“对象”类型的参数不可分配给“JSON”类型的参数 Httpclient GET
【发布时间】:2019-01-28 02:10:10
【问题描述】:

您好,我正在开发一个 Angular 6 + Flask 应用程序,我遇到了这个问题:

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

当我的代码这样做时:

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);
    });
  }

所以基本上当组件加载时,我向我的 python 服务器发出请求以获取一些以 JSON 格式返回给客户端的数据,但 angular 似乎认为“数据”是对象的类型,所以我无法添加它到我的 JSON 列表中

【问题讨论】:

    标签: json angular typescript angular-httpclient


    【解决方案1】:

    你必须投射它:

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

    【讨论】:

      【解决方案2】:

      您需要将数据转换为 JSON。 尝试使用 data.json,如下所示。

      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);
      });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-24
        • 2021-06-14
        • 2021-11-06
        • 2021-08-05
        • 2021-07-07
        • 1970-01-01
        相关资源
        最近更新 更多