您好,我正在使用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似乎认为'data'是Object的类型,因此我无法添加它到我的JSON列表中
答案 0 :(得分:3)
您必须将其投射:
this.httpClient.get<JSON[]>('http://127.0.0.1:5002/messages/mqtt').subscribe(data => {
答案 1 :(得分:0)
您需要将数据转换为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);
});
}