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

How to access parent slider variables in an Angular component

I've developed a slider as the parent component with multiple child components. See the demo here: https://stackblitz.com/edit/angular-ivy-gcgxgh?file=src/app/slide2/slide2.component.html Slider in the parent component: <ng-container *ngFor=&quo ...

Convert Ajax null value to NoneType in web2py

Every time I save information on a page, an AJAX request is sent with all the necessary data to be stored in the database. The format of this data looks similar to this example: {type: "cover", title: "test", description: null, tags: null} However, when ...

jQuery.ajax Failure Response

When using MVC on the server side and calling a function with jQuery.Ajax that returns JSON, an exception is being thrown. How can I invoke the error handling function of Ajax by sending something back in the return JSON function? MVC Function public Jso ...

Tips for setting up chrome-app typings in Typescript 2

I am looking to eliminate the typings in our Typescript project. After successfully removing most typings dependencies with Typescript 2, I'm left with just one for chrome-app: https://github.com/uProxy/uproxy/compare/master...fortuna:master When usi ...

Exploring Iframes within Angular2

import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: `<h1>Greetings, {{name}}!</h1> <iframe src="http://example.com/Home?requestId=+[testRequestId]+" allowfulls ...

Could someone please explain why my ajax is not functioning properly?

I have been working on an AJAX function to pass input values from one page to another. However, I am facing a challenge where the value is not being passed as expected after redirection. Despite my efforts, I cannot figure out why it's not functionin ...

Despite encountering the 'property x does not exist on type y' error for Mongoose, it continues to function properly

When working with Mongoose, I encountered the error TS2339: Property 'highTemp' does not exist on type 'Location' when using dot notation (model.attribute). Interestingly, the code still functions as intended. I found a solution in the ...

What is the best way to filter specific data types when using ngFor in Angular?

As I loop through the array named "fruits," which contains objects of type "FruitService" that I created, I want to display each element. However, when I delete them (I know it's strange, no database involved), they turn into type "undefined" and star ...

What is the best way to manage the loading and unloading of JavaScript within dynamically loaded partial pages?

Utilizing jQuery and history.js, I manage seamless transitions between partial pages to prevent entire document reloads. Some of these partial pages include unique javascript files. Despite successful page transitions, remnants of executed javascript linge ...

Having trouble getting `npm start` to work for the Lite-server?

As a newcomer to Angular and web programming, I attempted to replicate the quickstart project on github/angular by using "npm start" to initiate lite-server. However, following a tutorial [link] (https://www.youtube.com/watch?v=-zW1zHqsdyc&t=804s), I ...

Issue with character encoding in Primefaces AJAX

After finding a solution to an issue in my previous post, I encountered a new problem when using Primefaces' commandButton on certain forms. Despite including a custom Filter in the chain, Primefaces seemed to ignore charset settings, resulting in inc ...

Subject fails to subscribe to the change

There are two components in my project that share a common service. shared.service.ts // ..... skipping top level codes private pickAnalysisForBubble = new Subject<any>(); analysisForBubble$ = this.pickAnalysisForBubble.asObservable(); mapTo ...

What is the process to verify a password?

Hey everyone! I've successfully implemented control forms in my login.component.ts for handling email and password input. Now, I want to add these controls to my register.component.ts as well. Specifically, how can I implement controls for the passwor ...

The Angular template is throwing an error stating that c_r1.getCatType is not a valid function

Within my Angular project (version 9.1.0), I have a class structured like this: export class Contract { contractName: string; limit: number; public getCatType(): string{ if(this.limit > 0) return 'p'; return &ap ...

Create a recursive array structure that contains two distinct data types and specific guidelines

I have a unique array structure where the odd index always contains elements of TypeA and the even index always contains elements of TypeB. It is guaranteed that this array will always have an even length, never odd. The data structure of this array must ...

What is the best way to retrieve specific data based on their unique identifier?

Imagine having a table like this, with the following data: Id , Name , IsBillable 1 One 1 2 two 0 3. three 0 I have stored this data in a variable called masterData using the get method, and I am using it to populate a dropdown me ...

Ways to prevent encountering the "ERROR: Spec method lacks expectations" message despite achieving success

My Angular HTTP service is responsible for making various HTTP calls. Below is a snippet of the service implementation: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() expor ...

Modify the JS/JQuery variable by utilizing the data entered into an HTML input field

I have implemented a javascript/ajax request on my advanced search page. <script> // window.setInterval(function() // { $(function () { var SearchTerm = '<?php echo $_POST['Search']; ...

The error message "No provider found for MatSidenavContainer within mat-sidenav-content" is being

app.component.html <mat-side-nav-container> <mat-sidenav #sidenav> <mat-nav-list> <a mat-list-item [routerLink]="'/accounts'"> Accounts </a> <a mat-list-item [routerLink]="&ap ...

Adding up results from Ajax request based on specific criteria

I am performing an Ajax Request that retrieves data from two different databases. For example, I have 2 databases and my ajax request queries those databases to return the following information: [{"question_id":31,"columnheader":"joene_001","ct_yes":"2"," ...