Moving from Http to HttpClient in Angular4Changeover your Angular4

I recently migrated my Angular app to use the new HttpClient, but I'm encountering some challenges in achieving the same results as before with Http. Can anyone help me out?

Here's what I was doing with Http:

getAll() {
    return this.http.get(environment.API_DOMAIN + environment.CURRENCY_API_URL).map(res => {
        let response: ICurrenciesResponse = <ICurrenciesResponse> res.json();

        response.result = <Currency[]> res.json().result.map(service => {
            return new Currency(<ICurrency> service);
        });

    return response;
    });
}

The response is typed using the interface ICurrenciesResponse which looks like this:

import { IGenericResponse } from '../igeneric-response';
import { Currency } from '../../classes/currency';
export interface ICurrenciesResponse extends IGenericResponse {
    result?: Currency[]
}

As you can see, the interface extends IGenericResponse and consists of an array of Currency objects. To properly set this array, I had to map it again to create new Currency objects. This method worked well for me.

Now, after switching to HttpClient, my getAll function looks like this:

getAll(): Promise<ICurrenciesResponse> {
    return this.http
        .get<ICurrenciesResponse>(environment.API_DOMAIN + environment.CURRENCY_API_URL)
        .toPromise();
}

However, now my Currency array is not being properly set as an array of Currency objects. Shouldn't HttpClient automatically cast the data based on the defined interface in the get method? If not, what would be the best approach to achieve the same functionality as before with Http? Should I use subscribe() instead of toPromise() and process the data in a similar manner as before?

Thank you in advance!

Answer №1

The HttpClient does not automatically create instances from data inside the response; instead, it tries to determine the appropriate content-type for the response.

To create instances from the response data, you still need to use the map operator. However, the .json() call should be removed in this process.

getAll() {
    let url = environment.API_DOMAIN + environment.CURRENCY_API_URL;
    return this.http
        .get<ICurrenciesResponse>(url)
        .map(response => {
            if(Array.isArray(response.result) {
              response.result = response.result.map(service => new Currency(service));
            }
            return 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

Enhance the Component Props definition of TypeScript 2.5.2 by creating a separate definition file for it

I recently downloaded a NPM package known as react-bootstrap-table along with its type definitions. Here is the link to react-bootstrap-table on NPM And here is the link to the type definitions However, I encountered an issue where the types are outdate ...

Issues with naming in Gulp, Angular2 Final, and Visual Studio: "Cannot find name" and "Duplicate identifier" errors

Recently, I updated my project to utilize the final release of Angular 2 and also upgraded Visual Studio to use TypeScript 2.0.3 from the Tool -> Extensions and Updates manager. I compile my TypeScript using Gulp, and it compiles without any errors. Howev ...

Organize JSON data in Angular 6 from an observable based on a specific key

Note: While I am familiar with sorting a regular array of objects using .sort(), I am facing a challenge with an observable object that I am not accustomed to. My task involves retrieving a JSON array of objects with a service: import { Injectable } from ...

Transition your Sequelize migrations to TypeORM

I'm currently in the process of transitioning a Node.js application from vanilla JS to Nest.js. In our previous setup, we used Sequelize as our ORM, but now we've decided to switch to TypeORM for its improved type safety. While exploring the Type ...

Binding textarea data in Angular is a powerful feature that allows

I am looking to display the content from a textarea on the page in real time, but I am struggling to get the line breaks to show up. Here is my current code snippet: app.component.html <div class="ui center aligned grid">{{Form.value.address}}< ...

Displaying data from multiple checkboxes in an Angular application using an array

I'm currently facing an issue with displaying checked data in an Array within my Angular application. Upon clicking the checkbox, I receive a true value, but unfortunately, the data does not display as it contains null values. For reference, here is ...

Problems arising from positioning elements with CSS and organizing list items

I've been working on creating a navigation sidebar using Angular and Bootstrap, but I'm having trouble getting my navigation items to display correctly. APP Component HTML <div class="container-fluid"> <div class="row" id="header"&g ...

What is the best way to securely store a sensitive Stripe key variable in an Angular application?

When implementing Stripe payment system in my Angular App, I often wonder about the security of storing the key directly in the code as shown below. Is this method secure enough or should I consider a more robust approach? var handler = (<any>windo ...

Issues arise with file compilation in Angular 5

I want to apologize in advance for my English. I am encountering a problem when running `ng build --prod` on my Angular project. The following errors are being returned: ERROR in Error: Error: Internal error: unknown identifier undefined at Object. ...

aiplafrom struggles to establish a customer using Vite alongside Vue and TypeScript

I'm currently experimenting with Gemini Pro on Vite + Vue + TS, but I encountered an issue when attempting to create an instance of PredictionServiceClient. The error message displayed is Uncaught TypeError: Class extends value undefined is not a cons ...

It seems that every time you save data in Angular, the local storage array gets overwritten

While using Angular, I encountered an issue with saving to local storage. The code works fine for saving items initially, but on refreshing the page and trying to add more objects to the local storage array, it overwrites instead of appending. Can you help ...

Conditional type/interface attribute typing

Below are the interfaces I am working with: interface Movie { id: number; title: string; } interface Show { title: string; ids: { trakt: number; imdb: string; tmdb?: number; }; } interface Props { data: Movie | Show; inCountdown ...

Access a router and showcase a new URL in the browser using Angular 2

When using the router.navigate method to navigate to a specific path, it is possible to display a different URL in the browser than the one being navigated to. For example, if I want to navigate to the path /open/quote using this.router.navigate(['/o ...

Angular Error: "Provider's ngAfterViewInit method is not defined at callProviderLifecycles"

I encountered an error: evt = TypeError: provider.ngAfterViewInit is not a function at callProviderLifecycles while working on my Angular project. What's strange is that I do not have an ngAfterViewInit method, nor do I have the corresponding impl ...

Is it possible to both break down a function parameter and maintain a named reference to it at the same time?

When working with stateless functional components in React, it is common to destructure the props object right away. Like this: export function MyCompoment({ title, foo, bar }) { return <div> title: {title}, ...</div> } Now ...

Vue 4 and TypeScript: Dealing with the error message 'No overload matches this call'

In my Vue-Router 4 setup, I am trying to combine multiple file.ts files with the main vue-router (index.ts) using TypeScript. However, it throws an error that says "TS2769: No overload matches this call. Overload 1 of 2, '(...items: ConcatArray[]): ne ...

Problems with installing ambient typings

I'm having trouble installing some ambient typings on my machine. After upgrading node, it seems like the typings are no longer being found in the dt location. Here is the error message I am encountering: ~/w/r/c/src (master ⚡☡) typings search mo ...

Grunt Typescript is encountering difficulty locating the angular core module

Question Why is my Grunt Typescript compiler unable to locate the angular core? I suspect it's due to the paths, causing the compiler to not find the libraries in the node_modules directory. Error typescript/add.component.ts(1,25): error TS23 ...

The Angular HTML Autocomplete feature is not functioning as intended when hosted on a CDN in Chrome, despite setting it to "nope" or "off"

When setting Autocomplete to "nope" or "off" in my input box for surname, I'm still able to select from the autocomplete list. This issue occurs when accessing our Ui app through CDN at link [https:// Xyz. net], but works correctly when accessing it d ...

Why does my Observable remain perpetually unfulfilled?

I recently started learning javascript and came across the Angular 2 Documentation where I discovered that Promises can be replaced with Observables. While experimenting with a simple code, I noticed that in addition to the expected result, I am also getti ...