How to Fetch Data/Values from the Promise Object in Angular 6?

What I have is a simple registration page, which registers users and adds the form data into the db. What i want is to show the list of user details, for which i have a register component and a listing service. Here is my 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);
    }


}

Alerting "alert(this.data)" gives me [object Promise], so my question is how to fetch the data from this.data which is a promise object ?

My service is, listing.service.ts :

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);
    }
}

2 answers

  • answered 2018-07-11 05:52 Wesley Coetzee

    Your issue is in your service.

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

    You are calling extractData and handleError functions without the (), which has nothing to do with the solution to your issue, it's just a point I'm raising. You also do not need to call those functions at all, since you want to return the promise.

    The following code should work:

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

    You are already handling the .then() inside your component.

  • answered 2018-07-11 05:58 Fouad Kajj

    Try this :

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

    Use the following line in your service:

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