Angular 5 HttpClient fails to send a request

I'm encountering an issue with HttpClient while using Angular 5. The problem is that HttpClient doesn't seem to send any request (no xhr log appears in the console) on two specific components. However, it works perfectly fine on other components.

When I call the ApiService POST method (a custom service acting as a wrapper for HttpClient) from Component A, everything runs smoothly. But when calling the same method from Component B, HttpClient appears to freeze.

My application has numerous components utilizing ApiService and all dependencies are injected correctly. I'm puzzled about what could be causing this problem.

--- reply

ApiService.ts

@Injectable()
export class ApiService
{
    private errorListeners : Map<string, Array<(details ?: any) => any>> = new Map<string, Array<(details ?: any) => any>>();

    public constructor(private http: HttpClient)
    {

    }

    public post<T>(path : string, data : any, urlParams : any = null) : Observable<any>
    {
        return this.http.post<T>(`${environment.api.path}${path}`, data, {
            params: urlParams
        }).catch(this.catchErrors()).map(response => {
            if (response['Error']){
                throw response['Error'];
            }

            return response;
        });
    }

}

-- Component

   @Component({
    selector: 'login-register-component',
    templateUrl: './register.component.html',
    styleUrls: [
        './../../assets/main/css/pages/login.css'
    ]
})
export class RegisterComponent implements OnInit, OnDestroy
{

public constructor(private route: ActivatedRoute,
                       private router: Router,
                       private userService : UserService,
                       private apiService: ApiService
    )
    {
        this.apiService.post('/some-endpoint', null, {}).subscribe(res => {
console.log(res);

});

}

Even when directly injecting HttpClient into the Component, HttpClient fails to work properly.

-- Another component within the same module example call: (it works)

public loginTraditionalMethod(emailAddress : string, plainPassword : string)
    {

        this.apiService.post('/auth/email', {
            email: emailAddress,
            password: plainPassword
        }, {}).subscribe(res => {
           console.log(res);
        })

    }

Answer №1

I encountered a similar issue where no xhr request was being made after subscribing to an http.get(). This particular request was for a forgotten password feature, and it turned out that I wasn't actually connected to the app at the time.

It appears that the http token interceptor was intercepting the request and returning an empty Observable if it didn't detect an active session.

You never know, this information could potentially be useful to someone else facing a similar problem...

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

Interactive Requirement 6 UpdatePanel Requires Manual Mouse Movement for Refresh Post-Asynchronous Call

Our team is currently confined to using IE6 and unable to switch to a different browser. We've encountered an issue in our application where, after a postback occurs within our updatepanel, the browser appears to be resetting the DOM. One select box s ...

Exploring the Power of ForkJoin in RXJS with Complex Data Structures

I'm looking for a solution using forkJoin to execute an array of objects containing key-value pairs where the value is an observable. The goal is to have each object in the array result in the same key with the corresponding value being the outcome of ...

What is the best way to display a selected checkbox in an AJAX editing modal?

Can someone assist me in loading the checked checkboxes in an edit modal? I am using checkboxes to assign multiple roles in my system. Everything was working fine, but I encountered an issue with my edit modal where the checkboxes appear blank and unchecke ...

How can I integrate date and time pickers in the view using CodeIgniter?

Trying to add date and time data into the database using a date and time picker. After dumping the results in the controller to ensure all fields are selected, I encountered an issue where only the time is being picked and the data is not being inserted. T ...

What is the relationship between directives, templates, and ViewContainers in Angular?

I have implemented a basic functionality in my component where numbers are injected after a delay using a custom directive called *appDelay It is known that the Angular syntax hints with * will de-sugar into something like this: <ng-template ...> .. ...

Mongoose version 5.11.14 is causing TypeScript error TS2506 when attempting to utilize async iterators, requiring a '[Symbol.asyncIterator]()' to be present

I have decided to stop using @types/mongoose now that I've discovered that mongoose 5.11 already includes type information. However, when I attempt to run my code through tsc, I encounter TypeScript issues specifically with the following line: for aw ...

Error event encountered during development of React.js/Next.js application

When building on my local server everything works fine, but when I try to build on a production Linux server, I encounter the following error: > next build ...

most effective method to link table header to corresponding table row within this specific data organization

In my current project, I have a table component that relies on two data structures to create an HTML table: one for the table schema (paymentTableMetadata) and one for the table data (paymentTableData). To simplify the process, I have hardcoded these data ...

Troubleshoot Angular2 modules efficiently using source mapping features

Is there a way to debug Angular2 module code using TypeScript source mapping in the browser? After installing my project with the "npm install" command following the steps in https://angular.io/guide/quickstart, I noticed that while source mapping is ava ...

Exploring the jQuery load function paired with the Bootstrap navbar highlighting active pages

I recently implemented a bootstrap navbar on my website, and to easily update the content within it, I placed it in a separate file called nav01.php. However, I encountered an issue when trying to mark the active page in the navbar once I loaded it into ot ...

top solution for transferring large files over HTTP(S) with PHP (POST) initiated through the shell

I need to configure an automated backup system using PHP. The goal is to be able to "POST" a zip file request to another server using http/s, in order to back up an entire website (including its database). I want to set up a cron job to periodically send t ...

Generate web pages and content components dynamically using Ajax or Front-End in Typo3

Can new pages or content elements be generated programmatically using Ajax from a headless front-end in Typo3? I'm exploring the capabilities and constraints of Typo3. ...

What is the best way to invoke the draw() method of Datatables with Ajax?

In my Django application, I am working on implementing the draw() method from datatables using AJAX. Both datatables and AJAX are functioning properly. However, whenever I create a new object and call the draw() method to refresh the table with the newly c ...

Incorporating D3.js into Angular 6 for interactive click events

Currently working on building a visual representation of a tree/hierarchy data structure using d3.js v4 within an Angular environment. I've taken inspiration from this particular implementation https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5e ...

Product pages created with PHP, such as displaying as: Page: [1] 2 3 4

I am working on a product page created with WordPress that fetches products and displays them. However, I want to restrict the number of products visible at once. Code for generating with WordPress/PHP: $pages = get_pages(array('parent' => $ ...

Maintaining the generic types in mapped types in TypeScript

In my current project, I have a unique design where a class contains instance methods that act as handlers, each representing a specific operation. These handlers take a reference as input and assign the output to a second parameter. To simplify this proce ...

Encountering issues with the transmission and retrieval of ajax data in Struts 2 framework

Currently, I am attempting to transmit data through ajax and then retrieve the same using ajax. Below is the snippet of my ajax code: $.ajax({ url:"getSampleData", type:'GET', data : {'var':cellValue}, ...

Creating a stepper module in Angular 6

Looking for assistance from Angular experts app.component.html <app-stepper [activeStep]="0"> <app-step [sid]="0"> <div>iam step 1</div> </app-step> <app-step [sid]="1"> <div>iam step 1& ...

Despite the presence of the element, ngIf fails to render it on the screen

{{ element.number }} <div *ngIf="element.number"> 123 </div> Even though the server is sending the number, it's not displaying 123 as expected. Tried updating the ngIf to: *ngIf="element?.number" What could ...

Error: Invalid character '&' after initializing create-t3-application bootstrap

After initiating a new next.js app with the command npm create t3-app@latest, I encountered an unexpected syntax error when running the app using npm run dev. The error displayed was SyntaxError: Unexpected token '??='. Additionally, my console o ...