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

ngModelChange not triggered when updating the model from a component

I am currently exploring Angular and trying to grasp the concept of connecting different controllers to update their values based on changes in one controller. In a specific scenario, I have a form with ngModel and I am attempting to utilize ngModelChange ...

Conditional types can be used as type guards

I have this simplified code snippet: export type CustomType<T> = T extends Array<unknown> ? {data: T} : T; function checkAndCast<T extends Array<unknown>>(value: CustomType<T>): value is {data: T} { return "data" ...

Ways to dynamically apply styles to the component tag depending on the visibility of its content

Consider a scenario where you have a component with logic to toggle the visibility of its contents: @Component({ selector: 'hello', template: `<div *ngIf="visible"> <h1>Hello {{name}}!</h1></div>`, styles: [`h1 { fo ...

Updating displayed content based on orientation switch

Two components, A and B, are displayed simultaneously - A on the left and B on the right - when the device is in landscape mode. In portrait mode, either A or B will be displayed based on user selection. The components can transition from A to B and vice v ...

Determine rest parameters based on the initial argument

Struggling to generate a solution that infers the arguments for an ErrorMessage based on the provided code input. ./errorCodes.ts export enum ErrorCodes { ErrorCode1, ErrorCode2, ErrorCode3 } ./errorMessages.ts export const ErrorMessages = { [Err ...

Retrieve a variable in a child component by passing it down from the parent component and triggering it from the parent

I'm struggling to grasp this concept. In my current scenario, I pass two variables to a component like this: <app-selectcomp [plid]="plid" [codeId]="selectedCode" (notify)="getCompFromChild($event)"></app-select ...

Angular 4: preventing button click until form validation is successful

I am facing a situation where I have a form with required fields and 2 buttons: one button is for submitting the form, and the other button is for downloading a file. When the form is not valid, the submit button is disabled until the form becomes valid: ...

The ultimate guide to testing the export feature using Karma-Jasmine in Angular4

Hello everyone, I'm new to unit testing with Karma-Jasmine in Angular and I've encountered a problem that I hope you can help me with. I have a .ts file called example.constants.ts which contains a function for generating a random ID. Here is th ...

Typescript encounters an overload error on the Accumulator argument while using reduce operation

I encountered the following code snippet: const foo = ( fields: { [key: string]: string, } ) => { const { one, two } = Object.values(fields).reduce( (acc, field) => { if (isOne(field)) { return { ...acc, two: [...acc.two, ...

The module named "mongoose" does not have any member called 'PaginateResult' exported

I'm facing an issue while trying to add the necessary types for "mongoose-paginate" in my Angular 4 project setup with "angular-cli". The problem arises when Webpack throws an error. import {PaginateResult} from "mongoose"; ... getAll(page: number) ...

Availability of variables and declaration of functions

I'm having trouble accessing a variable in my Angular project. I am new to this, so please bear with me. Here's an overview of my project: app.component.html: <div> <ul> <li *ngFor='let var1 of Fcomponent' >{{var1}} ...

Having trouble getting POST requests to work in Angular 8 for unknown reasons

Hey there! I'm currently experimenting with using POST requests to an API in Angular for the first time, but unfortunately it's not working as expected. I've checked out some other examples of code and everything seems fine. Here is a snipp ...

Issue with `rxjs/Subject.d.ts`: The class `Subject<T>` is incorrectly extending the base class `Observable<T>`

I found a sample template code in this helpful tutorial and followed these two steps to get started - npm install // everything went smoothly, created node_modules folder with all dependencies npm start // encountered an error as shown below- node_mo ...

Querying data conditionally with Angular rxjs

I have a json file that contains multiple arrays structured like this: { A[] B[] C[] ... } This is the query I am using: myFunction():void{ this.apiService.getData() .pipe( map((response: any) => response.A), // to access to the &ap ...

Encountering a script error when upgrading to rc4 in Angular 2

After attempting to update my Angular 2 version to 2.0.0.rc.4, I encountered a script error following npm install and npm start. Please see my package.json file below "dependencies": { "@angular/common": "2.0.0-rc.4", "@angular/core": "2.0.0-rc.4", ...

Advantages of using ConfigService instead of dotenv

What are the benefits and drawbacks of utilizing @NestJS/Config compared to using dotenv for retrieving environment variables? Although I can create a class to manage all envvars in both scenarios, is it necessary? I am aware that @NestJS/Config relies on ...

I encountered an issue when attempting to display a validation message on an Angular form

As I work on creating an Angular form and implementing validation, I encountered an issue when attempting to display a message when a field is left empty. My approach involved using ng-for in a span tag, but unfortunately, an error occurred. Here is the H ...

Tips for successfully passing a prop to a custom root component in material-ui@next with TypeScript

Is there a way to properly render a ListItem component with react-router Link as the root component? Here's the code snippet in question: <ListItem to="/profile" component={Link} > Profile ...

Make sure to wait for the store to finish updating the data before accessing it. Utilize RxJS and Angular

Greetings! I am currently working with Angular and RxJS, and I'm trying to find a solution to wait for the store's data to be updated after an action is dispatched in order to perform some operations using that data. Below you can see a snippet o ...

Unable to sign out user from the server side using Next.js and Supabase

Is there a way to log out a user on the server side using Supabase as the authentication provider? I initially thought that simply calling this function would work: export const getServerSideProps: GetServerSideProps = withPageAuth({ redirectTo: &apos ...