Issue with triggering Observable during an Angular 2 HTTP call

In my current setup using Ionic 2 with Angular 2, I have the following method implementation:

private login(params: any, url: string){
    var p = new Promise<JsonResult>((resolve, reject) => {
        let body = JSON.stringify(params);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        this.http.post(url, body, options)
            .timeout(10000, new Error('Timeout exceeded during login'))
            .subscribe((res) => {
                let json = new JsonResult().deserialize(res.json());
                resolve(json);   
            }, (err) => { 
                reject(err);
            });
    });
    return p;
}

Despite my efforts, it seems that the subscribe function is not behaving as expected. The error handler does not trigger, even after the timeout limit has been surpassed.

I'm wondering if this issue is a common one or if there might be an error in my code structure?

Any assistance on this matter would be highly valued.

Answer №1

If you're looking to implement a Promise, my approach would be as follows:

private login(params: any, url: string){
        let body = JSON.stringify(params);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this.http.post(url, body, options)
            .timeout(10000, new Error('Timeout exceeded during login'))
            .catch(err => {
              console.log(err);
              return Observable.of([]));
            })
            .map((res) => {
                return new JsonResult().deserialize(res.json());
            }) 
            .toPromise();
}

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

The designation of 'Observable<Observable<Object[]>>' does not match the type of 'Observable<Object[]>'

I was previously working with Angular 2/4 without any issues. However, after upgrading to Angular 7, I started encountering this error consistently across my application. What could have caused this sudden problem? Type 'Observable<Observable<O ...

Adjust the dimensions of an Angular Material 2 dialog by updating the width or height

Is there a way to adjust the dimensions of an open Angular Material 2 dialog, either its width or height? I attempted to modify the size of the dialog by obtaining a reference to it and using the updateSize method within the dialog. Unfortunately, I belie ...

Error message: The function URL.createObjectURL is not recognized in this context | Issue with Antd charts

Currently, I am working on integrating charts from antd into my TypeScript application. Everything runs smoothly on localhost, but as soon as I push it to GitHub, one of the tests fails: FAIL src/App.test.tsx ● Test suite failed to run TypeError: ...

Replicating JavaScript functions with the power of Ajax

I'm facing an issue with Bootstrap modal windows on my page. The modals are opening and closing successfully, but the content inside them is fetched through AJAX as HTML. For example, there's a button in the modal: <button id="myBtn"> and ...

`What exactly do auth.guard.ts and the AuthenticationService do in Angular 8?`

import { Injectable } from '@angular/core'; import { AuthenticationService } from './_services'; import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; @Injectable({ providedIn: & ...

Implementing strict validation for Angular @Input by allowing only predefined values

I am facing an issue where I receive a string value as a parameter in a component, but I want to restrict the possible values that can be passed as a parameter, similar to using an enum. Currently, I have: @Input() type: string = ''; However, ...

Error encountered when sending AJAX post request to web server due to exceeding size limit

I encountered an error when attempting to post a base64 string: System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializerserializer,Stringinput,Typetype,Int32depthLimit) The JSON data includes base64 information and some details ...

Ensure that the alert for an Ajax JSON record count remains active when the count is

Trying out Ajax JSON for the first time has been a bit tricky. Even though I hard coded "Record: 1" on the server side, it keeps alerting me with a total record of 0. I'm not sure where I went wrong. Could it be an issue with how I passed the array da ...

Unable to fetch Twitter data using AJAX

Currently, I'm working on a web page that aims to display tweets from a specific city based on a user's search topic. The Twitter request is being sent successfully, with a response code of 200, and the response data is visible in the Chrome deve ...

Instructions for disabling editing for a specific cell within an inline editable row in primeNG

I am currently using PrimeNG DataTable with Angular, where the rows are editable as shown in the example in the documentation: https://www.primefaces.org/primeng/#/table/edit. However, I am facing an issue where I want to exclude one cell from being editab ...

Experimenting with error boundaries by utilizing the React Testing Library and Jest:

I am facing an issue while writing a test for my error boundary higher-order component (HOC). The problem arises when I mock throwing an error in my wrapped component, causing the test to fail because it recognizes the error as a genuine one instead of und ...

Detecting the clicked tab in Ajax Control Toolkit TabContainer - is it possible to determine which tab was selected?

I need some help with the TabContainer component from the Ajax Control Toolkit. My goal is to detect which specific tab a user has clicked on (such as by its index). If anyone has any insights on how to achieve this, please let me know! ...

Explore the functionality of Typescript unit testing in debug mode with the assistance of VSCode

I'm looking to debug my Typescript spec.ts file using vs-code. Typically, I run it from the terminal like this: npm run test:unit -- page.spec.ts But I want to add some console.log statements for debugging. Is there a way to do this in vs-code? When ...

React: Why aren't class methods always running as expected?

I created a class component that retrieves a list of applications from an external API. It then sends a separate request for each application to check its status. The fetching of the applications works well, but there is an issue with the pinging process ...

a dedicated TypeScript interface for a particular JSON schema

I am pondering, how can I generate a TypeScript interface for JSON data like this: "Cities": { "NY": ["New York", [8000, 134]], "LA": ["Los Angeles", [4000, 97]], } I'm uncertain about how to handle these nested arrays and u ...

How can we retrieve the target element for an 'onSelectionChange' DOM event in Angular 6?

When using Angular 6, I want to retrieve the "formControlName" of the corresponding element whenever the selection changes. HTML <mat-form-field *ngIf="dispatchAdviceChildForAdd._isEditMode" class="mat-form-field-fluid"> <mat-select ...

Move to the top of the page when the next action is activated

I am working with an Angular 8 application. Within the application, I have implemented navigation buttons for next and previous actions. My goal is to ensure that when a user clicks on the "next" button, the subsequent page starts at the top of the page ...

Oops! Looks like there was an issue with assigning to a reference or variable: Error: Uncaught (in promise)

I seem to be struggling with an issue that I believe may have been addressed before, but after reviewing other solutions, I am unable to pinpoint the error in my code. Any assistance in identifying my mistake would be greatly appreciated. <div class="j ...

I am looking to efficiently store various pieces of data in a database by utilizing a singular variable through JS, PHP, and AJAX for streamlined processing and management

I am not very familiar with the technical jargon in programming, so please bear with me if my question is a bit unclear. To provide more clarity, I have shared the code that I have already written. I will elaborate on the issue after presenting the code: ...

What is the best way to refer to a specific argument by implication within a function type?

Is there a way to extract the name of an argument from one type and use it in another type? For example, is it possible to achieve something like this: type F_v1 = (name: number) => boolean; type A = ["name", number]; //type F_v2 = (A[0]: A[1]) => bo ...