Troubleshooting the display of API-generated lists in Angular 8

I am encountering an issue in Angular 8 when trying to display my list on a page. Below is the code from my proposal-component.ts file:

import { Component, OnInit, Input } from "@angular/core";
import { ActivatedRoute, Params } from "@angular/router";
import { Proposal } from "./proposal";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs/Rx";
import { ProposalService } from "./proposal.service";

@Component({
  selector: "proposal-show",
  templateUrl: "proposal-show.component.html",
  styleUrls: ["proposal-show.component.css"],
  providers: [ProposalService]
})
export class ProposalShowComponent implements OnInit {
  constructor(
    private http: HttpClient,
    private route: ActivatedRoute,
    private proposalService: ProposalService
  ) {}
  @Input()
  proposal: Proposal;

  ngOnInit(): void {
    let proposalRequest = this.route.params.flatMap((params: Params) =>
      this.proposalService.getProposal(params["id"])
    );
    proposalRequest.subscribe(response => (this.proposal = response.json()));
  }
}

Additionally, here is my proposal.service.ts code:

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Proposal } from "./proposal";
import { Observable } from "rxjs/Rx";
import { throwError } from "rxjs";
import { map } from "rxjs/operators";
import { retry, catchError } from "rxjs/operators";

@Injectable()
export class ProposalService {
  private proposalsUrl = "http://localhost:3002/proposals";
  constructor(private http: HttpClient) {}
  getProposals(): Observable<Proposal[]> {
    return this.http.get<Proposal[]>(this.proposalsUrl).catch(this.handleError);
  }
  getProposal(id: number) {
    return this.http.get(this.proposalsUrl + "/" + id + ".json");
  }
  handleError(error) {
    let errorMessage = "";
    if (error.error instanceof ErrorEvent) {
      // client-side error
      errorMessage = `Error: ${error.error.message}`;
    } else {
      // server-side error
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    console.error(errorMessage);
    return throwError(errorMessage);
  }
}

Furthermore, this snippet is from my app.module.ts:

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { NgbModule } from "@ng-bootstrap/ng-bootstrap";
import { HttpClientModule } from "@angular/common/http";
import { AppComponent } from "./app.component";
import { HomepageComponent } from "./homepage/homepage.component";
import { AppRoutingModule } from "./app-routing.module";
import { DocumentsComponent } from "./documents/documents.component";
import { DocumentService } from "./documents/document.service";
import { ProposalComponent } from "./proposal/proposal.component";
import { ProposalNewComponent } from "./proposal/proposal-new.component";
import { ProposalShowComponent } from "./proposal/proposal-show.component";
import { ProposalService } from "./proposal/proposal.service";

import {
  NgbPaginationModule,
  NgbAlertModule
} from "@ng-bootstrap/ng-bootstrap";

@NgModule({
  declarations: [
    AppComponent,
    HomepageComponent,
    DocumentsComponent,
    ProposalComponent,
    ProposalNewComponent,
    ProposalShowComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    NgbModule,
    NgbPaginationModule,
    NgbAlertModule,
    HttpClientModule
  ],
  providers: [DocumentService, ProposalService],
  bootstrap: [AppComponent]
})
export class AppModule {}

This block of code represents the display page:

<div class="container">
  <div *ngIf="proposal" class="card proposal-card">
    <h1>{{ proposal.customer }}</h1>
    <div class="col-md-6">
      <div>
        <p>Hi {{ proposal.customer }},</p>
        
        <!-- Additional content omitted for brevity -->

      </div>
    </div>
  </div>
</div>

An error that I see in the console:

core.js:6014 ERROR TypeError: response.json is not a function core.js:6014 ERROR TypeError: this.proposal is not a function at SafeSubscriber._next (proposal-show.component.ts:27) at SafeSubscriber.__tryOrUnsub (Subscriber.js:185) at SafeSubscriber.next (Subscriber.js:124) at Subscriber._next (Subscriber.js:72) at Subscriber.next (Subscriber.js:49) at MergeMapSubscriber.notifyNext (mergeMap.js:69) at InnerSubscriber._next (InnerSubscriber.js:11) at InnerSubscriber.next (Subscriber.js:49) at MapSubscriber._next (map.js:35) at MapSubscriber.next (Subscriber.js:49)

Note: The API being utilized is functioning correctly without any issues. The API server is built using Rails.

Answer №1

core.js:6014 ERROR TypeError: response.json is not a function

The issue with the code seems to be related to calling `json` on the response when using `HttpClient`. Angular's HttpClient automatically handles parsing JSON responses, so there is no need for an explicit call to `json`. In this case, try subscribing to the response directly as shown below:

proposalRequest.subscribe(response => this.proposal = response);

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

How to dynamically incorporate methods into a TypeScript class

I'm currently attempting to dynamically inject a method into an external class in TypeScript, but I'm encountering the following error. Error TS2339: Property 'modifyLogger' does not exist on type 'extclass'. Here's the ...

The guidelines specified in the root `.eslintrc.json` file of an NX workspace do not carry over to the project-level `.eslintrc.json` file

In my main .eslintrc.json file, I have set up some rules. This file contains: { "root": true, "ignorePatterns": ["**/*"], "plugins": ["@nrwl/nx", "react", "@typescript-eslint", &qu ...

Angular is programmed to detect any alterations

Upon detecting changes, the NgOnChanges function triggers an infinite service call to update the table, a situation that currently perplexes me. Any assistance on this matter would be greatly appreciated. Many thanks. The TableMultiSortComponent functions ...

Extracting Raw Body from Stripe Webhook in NextJS

I'm feeling frustrated trying to get a raw body passed for the Stripe webhook in NextJS! Despite trying numerous solutions from various sources, I just can't seem to get it to work. Calling upon the developers with special powers (of which I am ...

Is it possible to link an HTML select element to a changing array in JavaScript?

Let's say I have an empty HTML select element. <select id="options"> </select> Can I link a JavaScript array to this select so that when the array is modified, the select options update accordingly? Alternatively, do I need to resort to ...

Incorrect Request Method for WCF json POST Request Leads to 405 Error (Method Not Allowed)

Hey there, I'm facing an issue with using Microsoft Visual Studio to create a WCF web service. Everything runs smoothly within Visual Studio, but when I try to connect to the service from outside, it fails to establish a connection. At first, I encoun ...

What is the best way to trigger a controller action when the datepicker's value changes?

Hello, I have a custom datepicker and I am trying to perform a calculation when the year is changed. The code provided below does not seem to work on onchange. I also attempted using the onchange attribute and calling a JavaScript function like this oncha ...

Transforming a vertical table into a horizontal layout

I'm facing an issue with transforming the database object for table display. My database contains a table structured like this. name total date Awoc1 100 9/14/2022 Awoc1 200 9/15/2022 Awoc1 300 9/16/2022 Awoc2 100 9/14/2022 Awoc2 ...

How is it possible for passing a number instead of a string to not result in a compilation error?

Here is some code that has caught my attention. It involves passing a number to a function that expects a string. const getGreeting: Function = (name: String): String => { return `hello, ${name}`; }; const x: number = 2 console.log(getGreeting(x)) ...

Did not adhere to regulations

Currently, I am in the process of developing a React app. However, when I attempt to initiate my project using npm start in the terminal, I encounter an error message on the browser. https://i.stack.imgur.com/wej1W.jpg Furthermore, I also receive an erro ...

Unable to locate component property

When passing props to my component that link to storybook, I encountered an issue where the object I pass in does not map, resulting in the error message: "TypeError: data.map is not a function". I realized that my object is not actually an &qu ...

Restore the button to its original color when the dropdown menu is devoid of options

Is it possible to change the button colors back to their original state automatically when a user deselects all options from my dropdown menu? The user can either uncheck each option box individually or click on the "clear" button to clear all selections. ...

What is the process for removing a registered user from Realm Object Server with the use of the Javascript library?

I have been searching online for a solution, but I haven't been able to find an answer. I am attempting to remove a user from ROS, however, I cannot locate a designated API for this task. The version of my realm-js is 1.10.3. If this feature does not ...

Divide JSON information into distinct pieces utilizing JQuery

$.ajax({ type: 'POST', url: 'url', data: val, async: false, dataType: 'json', success: function (max) { console.log(max.origin); } ...

Turning slide toggle on and off in Angular Material: A step-by-step guide

I am facing an issue where I have a list of mat slide toggles generated using a for loop. My goal is to disable all other slide toggles when one is clicked. Here is my code: HTML: <div class="row"> <div class="col-md-6 mt-2" *ngFor="let data ...

What is the method for setting and comparing collectionsjs equality?

I'm interested in utilizing the data structure. Within the factory method, you have the opportunity to specify equals and compare parameters: SortedMap(entries, equals, compare). Can anyone provide insight into what the expected formats for these pa ...

How can I retrieve a certain type of object property in TypeScript?

Imagine having a collection of flags stored in an object like the example below: type Flags = { flag1: string, flag2: string, flag3: boolean, flag4: number } // const myFlags: Flags = { // flag1: 'value 1', // flag2: 'value 1&ap ...

Comparing MediaObserver and BreakpointObserver: Understanding the variances

Upon conducting some research, I discovered that the recommended way to create responsive Material-themed UI is by using the Flex-Layout library (as discussed in this thread). The documentation indicates that this library offers the MediaObserver class for ...

File Upload yields a result of 'undefined'

Currently, I am utilizing Express File Upload. When attempting to send a post request to it, the error-handler returns an error indicating that no files were found. Upon logging console.log(req.files), it shows as undefined, causing the error to be sent ba ...

What is the best way to augment an AJAX array response with additional data?

I'm working on an AJAX request and I need to add additional properties to the response I receive. Can anyone offer some guidance? Here is the AJAX request code I'm using: var form_data = {}; $.ajax({ type: "GET", url: "../../../sample_ ...