Angular4 - Streamlined error tracking and management for all HTTP requests

I have created a customized wrapper class for handling all my http requests. The example provided only includes the get function:

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpResponse, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

/**
 * Custom HTTP client service for request customization
 */
@Injectable()
export class HttpClientService {
    private httpParams: HttpParams;
    private httpHeaders: HttpHeaders;

    constructor(
        private httpClient: HttpClient,
        private sharedService: SharedService) {
        this.httpParams = new HttpParams();
        this.httpHeaders = new HttpHeaders({ 'Access-Control-Allow-Origin': '*' });

    }

    public get<T>(url: string, httpParams: Array<Map<string, string>>) {
        return this.httpClient
            .get<T>(url, { params: this.appendHttpParams(httpParams), headers: this.httpHeaders })
            .subscribe(data => {
                console.log(data);
            },
            err => {
                console.log(err);
            });

    }

    private appendHttpParams(paramArray: Array<Map<string, string>>): HttpParams {
        paramArray.forEach((value: Map<string, string>, index: number, array: Array<Map<string, string>>) => {
            this.httpParams.append(value.keys[index], value.values[index]);
        });
        return this.httpParams;

    }
}

While this method functions correctly, calling it from a custom service using the following code snippet leads to an error:

this.httpClientService.get<StoredAppData[]>(this.configService.urls.fetchSettings, params)
    .map((response) => {
        this.storedAppData = response.json();
        console.log(this.storedAppData);
        return this.storedAppData;
    });

The TS2339 error is thrown, stating that Property 'map' does not exist on type 'Subscription'. Removing the .subscribe() would solve this issue, but central error handling on a single layer would then be challenging. What would be a recommended approach to handle this situation?

Answer №1

The issue lies in the type error identified within the code. It is important to note that a method intended to return an observable should not be returning a subscription:

const response$ = this.httpClient.get<T>(...)
response$.subscribe(data => ..., err => ...);
return response$;

Unless the intention is to return a hot observable, it is recommended that the subscribe method should not be called directly within the service. Instead, utilize the do operator for side effects:

The do operator serves as a tool for debugging Observables and executing side effects.

Note: Unlike subscribing to an Observable, using the do operator will not trigger the specified side effects unless the Observable is subscribed to. The do operator simply observes existing execution without initiating it, unlike subscribe which triggers the execution.

return this.httpClient.get<T>(...)
.do(data => ..., err => ...);

Answer №2

An alternative approach could involve swapping out the .subscribe() method with the .do() operator.

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

Adding an item into a list with TypeScript is as simple as inserting it in the correct

I am working with a list and want to insert something between items. I found a way to do it using the reduce method in JavaScript: const arr = [1, 2, 3]; arr.reduce((all, cur) => [ ...(all instanceof Array ? all : [all]), 0, cur ]) During the fir ...

What steps should be taken to guarantee that the view is created only after receiving values from the route params subscription?

How can I ensure that the View is only rendered after the subscription has received values? When clicking on the Edit button in MyComponent_1, Angular navigates to MyComponent_2. In MyComponent_2, the view contains a form whose values are dependent on rout ...

Exploring Angular: how RxJS enhances the power of making http requests

I'm currently working on a project using Angular 14.1, and I'm in need of creating a service that can retrieve data from multiple endpoints. The service needs to quickly fetch the required information as it will be used by a component. Here is m ...

Guide to releasing a NestJs library on npm using the nrwl/nx framework

Struggling with creating a publishable NestJS library using NX. Despite reading numerous documentations, I still can't figure it out. I've developed a NestJS library within an NX monorepository and now I want to publish just this library on NPM, ...

Slideshow through each item using Typescript and Angular8

I came across a solution in this carousel on by one link, but I'm struggling to work with the jQuery code even though I have JQuery installed in my project. For example: const next = jQuery(this).next(); I am looking to convert the JQuery code from ...

Struggling to extract the hours and minutes from a date in IONIC: encountering an error stating that getHours is not a recognized

I encountered an issue while trying to extract the hours and minutes from a date in Ionic. Below is the code snippet from my .html file : <ion-datetime displayFormat="HH:mm" [(ngModel)]='timeEntered1' picker-format="h:mm"></ion-date ...

What steps can I take to stop a browser from triggering a ContextMenu event when a user performs a prolonged touch

While touch events are supported by browsers and may trigger mouse events, in certain industrial settings, it is preferred to handle all touch events as click events. Is there a way to globally disable context menu events generated by the browser? Alternat ...

What is the most recent stable version of Angular recommended for utilizing ui-bootstrap?

I've been working on updating an older angular application and I'm interested in incorporating ui bootstrap for more advanced features. However, the current version of Angular used is 1.2.18 and any attempt to upgrade it to a higher version resul ...

Detecting Changes in Angular2 Component Attributes via Observables

When working with Angular 2 components that have input attributes defined using @Input, how can I create an observable to track changes to those input attributes (not to be confused with user input from a form)? export class ExampleComponent implement OnC ...

The behavior of Angular 4 CSS and JS changes upon refreshing the page

Every time I try to load a page with this particular script: this.router.navigateByUrl('/report-result/'+report.id); It appears that not all the CSS and JS files are being loaded properly. The bootstrap popovers don't show up, and some ele ...

I am encountering an issue where my TSX import is being declared but not read when I attempt to pass it to the Jest render method. Can anyone explain

My Jest test file includes a simple import of a TSX component in my nextjs 13 project. However, when I try to use the component as a TSX tag, an error occurs: "'Properties' refers to a value, but is being used as a type here. Did you mean ...

The issue arises when the ngif directive is triggered by the scrollDispatcher, causing the variable

While using Angular, I encountered an issue where the DOM (ngIf) was not responding to a variable flag change that was being triggered by scrollDispatcher for scrolling detection. Below is the code snippet of my testing: // html <div *ngIf="scrollS ...

Issue: [HPM] Context not recognized. Please specify a valid context such as: "/api" or ["/api", "/ajax"]

Suddenly, I am encountering the following error in my Angular 7 project without making any changes. Strangely, it was working fine until yesterday. Error: [HPM] Invalid context. Expecting something like: "/api" or ["/api", "/ajax"] at Object.matchContext ...

Streaming the result of Long Polling on HttpClient directly into a CSV file

Query 1: Is there a way to modify the behavior to invoke callbacks instead of using Observable.interval? Specifically, I want the next call to be made only after receiving a response from the server, even if it takes longer than the specified interval (e.g ...

Reactive Extensions - Incorporating interdependent synchronous calls into a fork join without the need for nesting

Looking for a way to avoid nesting synchronous calls that rely on each other and wanting to subscribe at the end result, similar to forkjoin. I came across a solution on stackoverflow (Wait for nested subscribe in angular before continuing with main subscr ...

Unnecessarily intricate: A Comparison and Enumeration of Elements in Arrays

I am facing a challenge with organizing arrays that represent categories and subjects. Each array represents a category, while each item within the array is a subject. For example: 4 Categories with Subjects ['A','B','D'] [&a ...

Trapped in the Google Maps labyrinth (Angular)

Hey there everyone! I'm currently working on an exciting angular application that integrates the Google Maps API. The goal is to create a feature that shows the 20 closest coffee shops based on the user's current location. However, I seem to be r ...

How do I manage two components on the same routing level in Angular with query parameters?

I am working with Angular and have two components placed at the same level of routing, both in the root directory. { path: '', component: HomeComponent }, { path: '', component: SearchComponent }, My challenge is to mak ...

Error: No injection provider found for function(){}!

After countless hours of setting up a custom AOT in Angular 7 project without CLI and debugging, I have encountered the following error: Uncaught Error: StaticInjectorError(Platform: core)[function(){}]: NullInjectorError: No provider for function(){}! ...

Exploring the capabilities of Dynamic Route integration with Server Side components using Supabase in Next.js

export default async function Page({ searchParams, }: { searchParams?: { [key: string]: string | string[] | undefined }; }) { // const searchParams = useSearchParams(); const id = searchParams?.p ?? "aaa"; // default value is "1" ...