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