HttpClient is not suitable for backend queries when working with Angular, unlike Http

Hey there, I'm diving into Angular and trying my hand at a REST API for the first time, so bear with me if something slips past me.

In this scenario, I have a Period object in Typescript and in C#, here they are:

Period TS:

export class Period {
    id: number;
    year: string;
    month: string;
    blocked: boolean;

    constructor(id: number, year: string, month: string, blocked: boolean) {
        this.id = id;
        this.year = year;
        this.month = month;
        this.blocked = blocked;
    }
}

Period C#:

public class Period
  {
    [JsonProperty(PropertyName = "id")]
    public int ID { get; set; }
    [JsonProperty(PropertyName = "year")]
    public string Year { get; set; }
    [JsonProperty(PropertyName = "month")]
    public string Month { get; set; }
    [JsonProperty(PropertyName = "blocked")]
    public bool Blocked { get; set; }

    public Period() { }
  }

Up to now, I've been able to fetch data from my database using Postman.

Postman: GET ->

https://localhost:5001/api/period/GetAllPeriods

[
  {
     "id": 122,
     "year": "2019",
     "month": "03",
     "blocked": false
  },
  {
     "id": 121,
     "year": "2019",
     "month": "02",
     "blocked": false
  }, ...
]

https://i.sstatic.net/kCw29.png

After some digging and testing, I've got the code below working. I retrieve my JSON data which I convert into Period objects in Typescript. Then, I display them on my page and everything's hunky-dory.

However, the Angular documentation states that Http is outdated and HttpClient should be used instead.

period.service.ts: Http

export class PeriodService {

  constructor(private http: Http) { }

  //Http
  getPeriods(): Observable<Period[]> {
    return this.http.get('/api/period/GetAllPeriods')
      .pipe(
        catchError(this.handleError),
        map(response => {
          const periods = response.json();
          return periods.map((period) => new Period(period.id, period.year, period.month, period.blocked));
        })
      );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
      console.error(error);
    }
    return throwError(
      'Something bad happened; please try again later.');
  };
}

I attempted to make use of HttpClient but encountered issues retrieving data in my service.

period.service.ts: HttpClient

export class PeriodService {

  constructor(private http: HttpClient) { }

  //HttpClient
  getPeriods(): Observable<Period[]> {
    return this.http.get<Period[]>('https://localhost:5001/api/period/GetAllPeriods')
      .pipe(
        catchError(this.handleError)
      );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
      console.error(error);
    }
    return throwError(
      'Something bad happened; please try again later.');
  };
}

https://i.sstatic.net/FeFPs.png

To clarify, while I can fetch JSON data from the API, when utilizing the HttpClient service, an error surfaces in the browser console indicating it's unable to locate the accessible data. It seems like the issue lies somewhere within the HttpClient service.

If you have any insights, I'd greatly appreciate it. Thanks in advance.

Answer №1

After struggling for days with a problem, I finally asked for help and immediately found the solution.

The issue was with this line of code:

import {HttpClientInMemoryWebApiModule} from 'angular-in-memory-web-api';

I realized that using HttpClientInMemoryWebApiModule was causing compatibility issues with HttpClient. Once I removed HttpClientInMemoryWebApiModule, my application started functioning correctly with HttpClient.

Now my application is running smoothly and is able to display the data properly.

Answer №2

Ensure that you include a subscribe method when calling the getPeriods() function within your component, as it operates on an observable type.

Don't forget to add this line in your code:
this.getPeriods().subscribe(response => { console.log(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

Using event.target to pass HTML form data to FormData is causing an error stating that the Argument of type 'EventTarget' cannot be assigned to a parameter of type 'HTMLFormElement'

Looking to extract data from a form and store it in FormData: const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); const formData = new FormData(e.target as HTMLFormElement); const value = formData.get(' ...

Calling the `firstValueFrom()` method in RxJS will keep the observable alive and not

Hey there, I'm currently having issues with using firstValueFrom(), lastValueForm(), and Observable.pipe(take(1)) in my TypeScript code with Angular 14 and RxJs 7.8.0. I am working with a Firebase server that provides stored image URLs via an API wit ...

Tips for executing various test methods in a single browser instance without having to shut it down (C#, SeleniumWebDriverz NUnit)

As a novice in the world of c# and Selenium, I have a query. Is it feasible to run multiple [TestMethod]-s in the same browser instance without closing it? For example, after completing "Can_Change_Name_And_Title", I would like to seamlessly proceed to "C ...

What specific compiler does Visual Studio utilize for creating solutions?

While researching JIT and AOT compilers, I came across information stating that the CLR in .NET utilizes JIT compilation. However, I also discovered that the build process in Visual Studio involves compilation, linking, and other tasks. I understand that ...

When using TypeScript, the ReactDOM.render function may not accept certain components

Summary In my TypeScript and React project, I have created the AppContainer.tsx component and exported it as default. In the file app.ts, where I am using ReactDOM to render it on the targeted dom element, I encounter some errors (refer to the image). For ...

Utilizing Dependency Injection in .NET8 to Inject Dual Instances of MongoDb Clients

I am seeking guidance on implementing Dependency Injection with .NET Core 3 to inject two instances of MongoDB Clients. I have a specific use case where I need to read data from Db1/collection1 and then save new information to Db2/collection2. In my startu ...

What is the general type that the empty array [] represents?

When using int[], string[], T[], this represents a generic array. An array is treated as an object like any other. What is the specific open generic type of []? I presume it is a form of syntactic sugar similar to Array<>, but I have not come across ...

Accessing unique identifiers from Firebase Database with AngularFire

My Firebase Database is structured as shown below: fire-demo-123 course 1 : "course1" 2 : "course2" 3 : "course3" -MzOn2s : "course4" I am currently using the following code to fetch the list component.t ...

When making a GET request using Angular HttpClient, an error message stating "No overload matches this call" may

One issue I am facing is with a GET method in my backend. When sending a request body as input, I receive a list of results in return. However, the problem arises in my frontend: search(cat: Cat): Observable<Cat[]> { return this.httpClient.ge ...

What is the reason behind having to refresh the page or switch to another tab for the field to display?

Currently, I am in the final stages of completing my update form. However, I am facing an issue with the conditional field. The select field should display a conditional field based on the selected value. The problem I'm encountering is that I need to ...

Error message 2339 - The property 'toggleExpand' is not recognized on the specified type 'AccHeaderContextProps | undefined'

When utilizing the context to share data, I am encountering a type error in TypeScript stating Property 'toggleExpand' does not exist on type 'AccHeaderContextProps | undefined'.ts(2339). However, all the props have been declared. inter ...

What solution does this offer to the state closure issue when using React hooks?

While reviewing the code in formik, I came across a solution for the stale closure problem with React hooks. function useEventCallback<T extends ( ...args: any[]) => any>(fn:T): T { const ref:any =React.useRef(); // we copy a ref to the call ...

Including a hyperlink in a table using Angular 8

I have a table with multiple columns, one of which is the "documents" column that contains downloadable files. How can I make just the document name clickable as a link? HTML <p-table #dt3 [columns]="colsPermessi" [value]="permessi" [paginator]="true" ...

Error in Angular 5: Cannot find property 'then' in type 'Observable<any>'

I encountered the following error message: "[ts] Property 'then' does not exist on type 'Observable'. How can I resolve this issue? Below is my Component code: getUsers(){ this.authService.getUsers().then((res) => { thi ...

What could be causing the TypeScript class property to be undefined?

Below is the code snippet I am working with: class FeedbackController { public homePage(req, res){ this.test(); res.send('Welcome to feedback service'); } private test(){ console.log('test called'); } } export de ...

Struggling to render the template inside a .vue file in a Vue.js + TypeScript project?

Is anyone familiar with setting up a Vue TS based project? I have encountered an issue where the template data is not being rendered in the browser's DOM. The project structure can be found in this repository: https://github.com/AndrewBogdanovTSS/typ ...

Angular 10 issue: Cart quantity in header shared component does not update when changed from another component

Whenever I click on the 'Add to cart' button, I want the number of items in the cart icon on the header component to increase. Currently, this only works when I refresh the page. In order to achieve this, I am using a cart service to store globa ...

Angular 2 Change Detection Issue: Value of expression has been updated post-check. Original value: 'over'. Updated value: 'side'

I'm encountering an error specifically in Firefox, but not in Chrome or IE. "Error: Error in ./DefaultLayoutComponent class DefaultLayoutComponent - inline template:2:14 caused by: Expression has changed after it was checked. Previous value: ' ...

Looking to utilize MiniJson to extract data from Json and then save it into a list for further processing

{ "participants": [ { "wins": 8, "losses": 1, "score": 264.5, "pro": false, "name": "albert" }, { "wins": 7, "losses": 1, "score": 214.5, "pro": false, "name": "mike" } I am attempting to parse t ...

Using Typescript in combination with snowpack may result in nullish coalescing operators being generated when targeting a version lower than ES2020

I've been working on compiling my TypeScript code/packages to ensure compatibility with Safari Version less than 14. After researching, I discovered that nullish coalescing operators (??) are not allowed in the targeted version. Despite changing my t ...