The parameter type 'Object' cannot be assigned to the parameter type 'JSON' in the HttpClient GET method

Hey there! Currently, I'm deep into developing an Angular 6 + Flask application and I've encountered a bit of a snag:

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

This issue arises when the following section of my code executes:

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

During the component's initialization process, a request is made to my python server to retrieve some data in JSON format back to the client. However, Angular appears to be under the impression that 'data' is an Object type and not matching it to my list of JSON.

Answer №1

To properly handle the response, you need to perform a cast:

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

Answer №2

To transform the information into JSON format, you should utilize data.json as shown in the example below.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Privileged" and "shared" within an Angular module

Without adding private before foo, loadBar, andtext, they are considered to be public by default in the component. export class RandomComponent { @Input() foo: string; @Output() loadBar = new EventEmitter(); text: string; } Is there any scenario whe ...

Add JSON elements to an array

Looking for help! {"Task": [Hours per Day],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]} Need to add these items to a jQuery array. I've attempted using JSON.parse without success. Typically, I can push parameters as follows: MyArr.push([& ...

Implementing error wrapper in typescript to handle failing promises with n retries

I have a wrapper function that calls an async function: function fetchAPI(arg1: number, arg2: number, arg3: string) { return new Promise((resolve, reject) => { try { myFetchFunction(arg1, arg2, arg3).then((r: any) => { if (!r) { ...

State array is being updated

In my main container, I am setting a context for its children : import React, {useRef, useEffect, useState, ReactNode, createContext, useContext} from 'react'; import Provider from "./Provider"; import Consumer from "./Consumer&quo ...

Dealing with JSON parsing in Android? Don't be surprised if Volley throws an error

I encountered a volley throw error while attempting to parse JSON data in a listview. It seems that the issue lies with my JSON data being in an object node, rather than an array node. JSON data: { "users": [{ "userId": 1, "name": "Dy ...

Ways to ensure that your Angular component.ts file is executed only after the body has completely loaded without relying on any external

I am attempting to add an event listener to an element created with a unique identifier using uuid, but I keep getting an error that states "Cannot read properties of null (reading 'addEventListener')" export class CommentItemComponent implements ...

Changing the background color of a selection in Angular can be customized by modifying

Is there a way to customize the background color of a select element in Angular? I would like to change the default grey background to white. How can this be achieved? Below is the code for my select element: <select id="areaOfExpertiseFilter" ...

Angular throws a NullInjectorError when a unit test fails due to issues with dependency

As a newcomer to Angular, I am struggling to grasp the concept of Dependency Injection (DI) and how it functions. My current challenge involves trying to pass a unit test successfully. Below is the code for the test; import { TestBed } from '@angula ...

Exploring the Power of TailwindCss in Storybook 6 for Angular Development

I am in the process of creating a component library using Angular version 11.2.8, and I'm attempting to integrate TailwindCss and Storybook 6. Despite trying various configurations, none seem to be working correctly for me. Whenever I run Storybook, ...

What is the best way to instantiate objects, arrays, and object-arrays in an Angular service class?

How can I nest an object within another object and then include it in an array of objects inside an Angular service class? I need to enable two-way binding in my form, so I must pass a variable from the service class to the HTML template. trainer.service. ...

Having trouble launching the node pm2 process manager on AWS Elastic Beanstalk, npm update verification did not pass

Having some issues with utilizing pm2 for managing processes in my typescript node application, deployed on elasticbeanstalk. Whenever a new instance is launched by pm2, the following shows up in the logs ---------------------node.js logs---------------- ...

An object may be null when its type is A or undefined, but we are certain it is not undefined

Since the release of version 4.8.4, the TypeScript compiler has been flagging an issue with the following code: type A = {v: number} function get_the_first<T>(xs: T[]): T | undefined { if (xs.length > 1) return xs[0]; else ...

Outputting individual values from a dictionary

Currently working on a challenge to print all strTeam values from the teams:[Team] dictionary. Appreciate any help or guidance on this issue. If you notice any other errors, please feel free to point them out. Thank you. import UIKit class ViewController ...

Is there a way to merge TypeScript code with C++ during compilation?

Currently, I have a project written entirely in C++. However, there is an additional file written in typescript because I couldn't find equivalent libraries in C++. This typescript file performs the following actions: It contains a typescript CLI cod ...

Ensure that only numbers with a maximum of two decimal places are accepted in Angular 2 for input

On my webpage, there are several input boxes where users can enter numbers. I need to prevent them from entering more than two decimal places. Although I tried using the html 5 input Step="0.00", it didn't work as expected. I am open to any TypeScri ...

Utilizing Angular RouterLink queryParamsHandling for managing optional parameters

Is there a proper way to combine the existing optional queryParams with an additional optional queryParam while linking in the template? Current URL: /search;brand=Trek Preferred link destination: /search;brand=Trek;start=1 (incrementing startCount) I a ...

Converting JSON data from ASP.NET MVC to a Canvas.js chart

Despite my efforts to find a solution by looking through similar posts, I am unable to resolve the issue. Within my asp.net MVC controller, I have a method called public object OfferChart() List<Det> obj = new List<Det>(); foreach ...

Guide on signing a JSON file using an E-Pass signature in Postman

While using the Postman API collection to send a file, everything was working well initially. However, I encountered an error after sending the file: "ITIDA Signature Invalid Signature • ISFX306 Document Signature Error : Invalid Signature Format. • 40 ...

Updating JSON files with new key-value pairs using Python

In my possession are a series of JSON files containing various data. Within these files, there is a specific key named 'BrowserInfo' which holds valuable information. My objective is to extract the details such as Title, Links, Browser, Platform, ...

When using `ng lint --fix=true`, the linting errors remain unresolved and are not fixed

Upon initializing a fresh project using "ng new" and adjusting tslint.json to utilize tabs instead of spaces, I encountered an issue where running "ng lint --fix=true" did not result in any changes to the .ts files: https://i.sstatic.net/yPJu2.png ng lint ...