Using the .json method in Angular 7 for handling responses

While attempting to implement the function getProblems to retrieve all problems within its array, I encountered an error message appearing on res.json() stating:

Promise is not assignable to parameters of type Problem[].

It seems that the function is treating the response as a promise and trying to map it into Problem[] using "res.json", which is then being passed into BehaviorSubject.

import { Injectable } from '@angular/core';
import { Problem } from '../models/problem.model';
import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject} from 'rxjs';
import { Observable } from 'rxjs';

@Injectable()
export class DataService {

private problemsSource = new BehaviorSubject<Problem[]>([]);

constructor(private http: HttpClient) { }

getProblems(): Observable<Problem[]> {
    this.http.get('api/problems')
      .toPromise()
      .then((res: Response) => {
        this.problemsSource.next(res.json());
      })
      .catch(this.handleError);

    return this.problemsSource.asObservable();
  }

On a side note, as someone new to Angular, I attempted to reuse some code from a previous project. Due to deprecation of certain APIs in Angular, the current code implementation is no longer functioning, and I am struggling to find a workaround.

Answer №1

If your response does not need any processing, you can follow the approach below:

fetchData(): Observable<Data[]> {
  this.http.get<Data[]>('api/data')
           .toPromise()
           .then((response: Data[]) => {
              this.dataStore.next(response);
           })
           .catch(this.handleError);
  return this.dataStore.asObservable();
}

Note: The use of .json() method with Http class has been deprecated and replaced by the angular HttpClient that automatically converts the response into a JSON object for typed return values.

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

What causes the component's constructor to be invoked multiple times instead of being efficiently reused by the router?

I came across this interesting article where the writer discusses how the router reuses components to avoid unnecessary DOM modifications: In order to prevent unnecessary changes to the DOM, the router will reuse components when the parameters of the co ...

Lack of y data in the Highcharts

I am facing an issue with retrieving yAxis data in Highcharts. You can view the fiddle at https://jsfiddle.net/LLExL/6496/. I have loaded Highcharts using the code below. $(function () { $('#RankingReportsHistory').highcharts( ...

Updating the data attribute of an object in HTML using Angular

I am trying to embed a PDF viewer inside a component. In order to dynamically update the PDF document within a sanitizer, I need to use an attribute with []. This works fine with images. <img src="assets/pic.jpg"/> <img [src]="'assets/pi ...

The issue lies with Express Mongoose failing to store the data

Encountering some issues when trying to save an object created in Express nodejs using mongoose. Despite receiving a confirmation that the object is saved, it cannot be located even after attempting to access it through the server. Express route for savi ...

Encountering a JSON_PARSER_ERROR when trying to call Google FCM using MobileFirstAdapter JS

I am working on integrating Google FCM Api for sending Push Notifications. Below is the snippet of code from my JavaScript file: function sendNotificationToUser() { var request={ path :'/fcm/send', method: 'POST&ap ...

Finding distinct outcomes from an already screened roster using AngularJS

I have an array containing objects structured like this: { "date":"11/11/2014", "time":"17.20.37", "car":"396", "driver":"Jenny", "from":"Old Office", "destination":"Log WH", "pax":"3","comment":"", "commenttime":"", "arrival":"17.20.48", "inserted":true, ...

Methods for applying a style property to a div element with JavaScriptExecutor in Selenium utilizing C#

I have been attempting to change the style of a div element using JavascriptExecutor in C#, but so far, nothing has happened. IJavaScriptExecutor js = (IJavaScriptExecutor)driver; IWebElement element = driver.FindElement(By.XPath("//div[contains(@class, ...

What is the best method for streaming files from Java to the browser while preventing the user from downloading and saving the file?

I'm new to this and feeling a bit lost. Here's the situation: I have a web app (built with JavaScript/Reactjs) and a backend (Java using Liferay API) The server contains files (File A, B, C, etc.) of various types: pdf, excel, audio, txt, etc. ...

Encountering difficulty selecting a dropdown sub-menu using Selenium WebDriver

I'm currently working on automating a website with selenium webdriver. The issue I'm encountering is that when I try to click on a menu item, the submenu pops up (actually a misplaced dropdown, UI issue), and although I can locate the element of ...

Develop a responsive image component with flexible dimensions in React

I am currently working on developing a dynamic image component that utilizes the material-ui CardMedia and is configured to accept specific height and width parameters. The code snippet I have is as follows: interface ImageDim extends StyledProps { wid ...

Angular 2: Creating a Reusable Object for Uniform JSON Structures

I am facing an issue with JSON data as I have 3 tables in my database named "dictionary" with the same structure but different column names: {"id":1,"test_1":"test"},{"id":2,"test_1":"lalala"} - first JSON {"id":1,"test_2":"****"},{"id":2,"test_2":"afe ...

Retrieve information from a JSON document

My project involves a bookStore with a list of books that I am working on. I am trying to extract all the book data from a JSON file and display them in a card view on a webpage. Although my code is error-free and seems to be functioning properly, the da ...

How can I efficiently update Vue data externally?

const app = createApp({ data() { return { unique_id: 0 } } }) I implemented an autocomplete feature on a specific input field. My goal is to send the chosen id to a Vue application when a label is selected. onSelectItem: ({label, value}) ...

What is the syntax for implementing React.forwardRef in a dynamic Anchor or Button component?

I am working on a component that can act as either a button or an anchor tag. However, I am facing challenges in implementing conditional typing for the ref. How can I resolve this issue and make the ref acceptable? type ConditionalElements = | ({ ...

When an array is prototyped as a member of a JavaScript object, it becomes a shared property among all instances

Is anyone else surprised by this behavior? It really caught me off guard... I was expecting prototyped arrays to be private to each instance of a class rather than shared across all instances. Can someone confirm if this is the intended behavior and provi ...

Vue.js does not support animation for the Lodash shuffle function

I'm having trouble getting the lodash's shuffle method to animate properly in Vue.js. I followed the code from the documentation, but for some reason, the shuffle occurs instantly instead of smoothly. When I tested the animation with actual item ...

What specific types of errors is this try-catch block designed to catch and manage?

// This function establishes a connection to MongoDB using Mongoose const connectToDatabase = (url) => { return mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Conn ...

What is the best way to update auto margins after resizing an element with Javascript?

I'm having an issue with a DIV on my webpage that is centered using margin-left and margin-right set to auto. When I try to resize the DIV, it no longer stays centered on the screen. <div id="content" style="margin-left:auto;margin-right:auto;widt ...

Is there a way to apply -webkit-text-fill-color using pure vanilla JavaScript?

My website features two a links, and I am utilizing JavaScript to set their href attributes. When there is no link provided, the color changes to black. However, in Safari on iPhone, achieving the correct color requires the use of -webkit-text-fill-color ...

Moving from traditional web pages to a mobile application using NextJS has brought about the error "rest.status is

Currently, I am in the process of upgrading from Next 13.2.5 to version 14.1.0 and switching to using app/api/example/route.js instead of pages/api/example.js. After making these changes, I encountered an error stating TypeError: res.status is not a funct ...