Tips for Retrieving Information from the Promise Object in Angular 6

I am currently working on a simple registration page to register users and save the form data into the database. My goal is to display a list of user details using a register component and listing service. Below is my implementation in register.component.ts:

import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { UserData } from '../userdata';
import { ListingService } from '../listing.service';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';

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

    role : any[];

    data : Promise<any>

    userdata : any[];

    constructor(private listingService : ListingService, private http : Http) { this.role = ["Admin","Super-Admin","User"] }

    selectedRole: Object = {};  

    ngOnInit() {
    }

    registerUser(form: NgForm)
    {
        //console.log(form.value);      
        let details = JSON.stringify(form.value);                       
        this.data = this.listingService.registerUser(details)
        .then((result) => {console.log(result); this.userdata = result;})
        .catch(error => console.log(error));

        alert(this.data);
    }


}

When I use "alert(this.data)", it displays [object Promise]. Can anyone guide me on how to retrieve data from this.data which is a promise object?

The listing.service.ts file for my service is as follows:

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
//import { toPromise } from 'rxjs/operators';
import { UserData } from './userdata';

@Injectable()

export class ListingService
{
    headers: Headers;
    options: RequestOptions;

    constructor(private http:Http)
    {

    }

    registerUser(details : any) : Promise<any>
    {               
        //alert(details);
        //this.headers = new Headers({ 'Content-Type': 'application/json;charset=utf-8', 
          //                           'Accept': 'q=0.8;application/json;q=0.9' });
        //this.options = new RequestOptions({ headers: this.headers });
        return this.http.post("http://localhost/Angular6http/UserDetails/src/app/data.php",details).toPromise().then(this.extractData).catch(this.handleError);
    }

    private extractData(res: Response) {

        //alert(res);       
        let body = res.json();
        //alert(body);
        return body || {};      
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error);
    }
}

Answer №1

The root of the problem lies within your service.

return this.http.post("http://localhost/Angular6http/UserDetails/src/app/data.php",details)      
  .toPromise()
  .then(this.extractData)
  .catch(this.handleError);

You have overlooked the fact that you are invoking the functions extractData and handleError without the required parentheses. This is not directly related to fixing your issue but it's worth mentioning. In reality, there is no need to call those functions at all since you simply want to return the promise.

This modified code snippet should resolve the problem:

return this.http.post("http://localhost/Angular6http/UserDetails/src/app/data.php", details)
  .map(res => res.json())
  .toPromise();

Remember that you are already handling the .then() method in your component.

Answer №2

Give this a shot:

    addUser(form: NgForm)
{
    //console.log(form.value);      
    let data = JSON.stringify(form.value);                       
    this.userService.addUser(data)
    .then((result) => {console.log(result); this.userData = result; this.dataResponse = result; alert(this.dataResponse);})
    .catch(error => console.log(error));


}

Add the following line to your service:

return this.http.post("http://localhost/Angular6http/UserDetails/src/app/data.php",data)

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

ngClass causing styling issue when applying styles

When I use class names like error and info, the CSS works fine. For example, in this Angular app (latest version) here: https://stackblitz.com/edit/github-i4uqtt-zrz3jb. However, when I try to rename the CSS classes and add more styles, like in the examp ...

Refreshing a token in Angular 8 without relying on a refresh token

Is there a secure method to update a token without using Refresh Tokens or OAuth? After a user authenticates against my API, I generate a JWT that is valid for a set amount of time. This token is then used in an interceptor to navigate through the protec ...

The lazy loading attribute for images in Angular 12 is not functioning as expected

When it comes to offscreen images, including those in the footer, I always make sure to use loading="lazy". I have experimented with applying this technique both with Client Side Rendering and Server-side Rendering (Angular Universal). Despite my efforts, ...

Extending the Model class in TypeScript with Sequelize

Currently, I am tackling a legacy project with the goal of transitioning it to Typescript. The project contains models that are structured as shown below: import Sequelize from "sequelize"; class MyModel extends Sequelize.Model { public static init(seq ...

Performing subtraction operations on decimal numbers in Typescript

I am currently working with a table that keeps track of changes in stock levels. In most cases, the changes are made using whole numbers (-1, -2, +2, +3) etc. However, there are some instances where fractions like +0.5 or -0.25 need to be accounted for. Th ...

Error encountered: Unable to start Angular 5 project - '$' not recognized

I recently downloaded a project and ran npm install. It was running smoothly on my work PC, but now I am facing an issue when trying to start it. The error that keeps popping up is: error TS2304: Cannot find name '$'. This problem is occurring ...

"VueJS: Difficulty in Ensuring Child Component Updates Along with Parent Component Changes

I am facing an issue with a Vue instance that passes an object to a child component. The child component contains a checkbox which, when clicked, triggers an event handled by the parent Vue instance to update the object passed to the child. According to th ...

Uniting 2 streams to create a single observable

I am in the process of merging 2 different Observables. The first Observable contains a ShoppingCart class, while the second one holds a list of ShoppingItems. My goal is to map the Observable with shopping cart items (Observable<ShoppingItems) to the i ...

Enhance the window.top functionality with TypeScript, enhance Visual Studio Code suggestions

In the previous project, an iframe was used for development. The top-level window contains several private attributes, and other pages interact through it. I now need to enhance the type of top in the iframe page using TypeScript. How should I modify the c ...

Retrieve parameters from the typeOf ngrx effects

I am currently dealing with the following code snippets: ngOnInit() { this.store.dispatch(new TutorialActions.GetTutorials(1, 20)); } export class GetTutorials implements Action { readonly type = GET_TUTORIALS constructor(public number: number, publ ...

If the main server page API for Angular is unavailable, the system will automatically redirect to an alternative

I am currently utilizing Angular CLI and I have a scenario where if the server for the main page API is down, I need to redirect the user to another page that I have created. Currently, there seems to be an issue with the server's main page functiona ...

Tips for exporting an array of dynamic JSON objects to CSV using Angular

I am facing a challenge in exporting an array of JSON objects to CSV as the number of key-value pairs can vary, leading to additional columns in some objects. Currently, I am using the Angular2CSV package for export functionality, but it requires all colum ...

Struggling with Angular 5 Facebook authentication and attempting to successfully navigate to the main landing page

I have been working on integrating a register with Facebook feature into an Angular 5 application. Utilizing the Facebook SDK for JavaScript has presented a challenge due to the asynchronous nature of the authentication methods, making it difficult to redi ...

What is the method to incorporate the current time into a date object and obtain its ISO string representation?

I'm using a ngbDatePicker feature to select a date, which then returns an object structured like this: {year:2020, month:12, day:03} My goal is to convert this date into an ISOString format with the current time. For example, if the current time is 1 ...

Having trouble locating the module while importing MP3 files in a React project

UPDATE The issue stemmed from my limited understanding of the environment I was working in, but the responses provided below may be helpful for others facing similar challenges. EDIT: It appears that there is a problem with trying to import an mp3 file in ...

Error encountered when using withRouter together with withStyles in Typescript on ComponentName

Building an SPA using React with Typescript and Material UI for the UI framework. Stuck on a recurring error across multiple files - TS2345 Typescript error: Argument of type 'ComponentType<Pick<ComponentProps & StylesProps & RouteCompo ...

Exploring Rxjs repeatwhen with a delay in action

I'm struggling to understand how repeatWhen and delay() work together. If you want to see my issue in action, click on this link and make sure to open the console. I tried using takeWhile to stop the repeatWhen stream before it gets to the delay ope ...

What is the method for transmitting a URL API from an ASP.NET Core server to my Angular 2 single application?

Is there a way to securely share the url of the web api, which is hosted on a different server with a different domain, from my asp net core server to my client angular2? Currently, I am storing my settings in a typescript config file within my angular2 ap ...

Ionic3 attempted lazy loading, however it failed due to the absence of any component factory

When implementing Lazy loading in Ionic3, the browser displays an error message after serving: Error: Failed to navigate - No component factory found for TabsPage. Have you included it in @NgModule.entryComponents? Below is the code snippet: app.modu ...

Enhance the visibility of an HTML element using a directive

A specific directive I've created has the ability to display or hide an HTML element. You can view the code on StackBlitz: <div *authorize="'A'"> This will be visible only for letter A </div> Here is the Authorize directive i ...