如何在Angular 6中从Promise对象获取数据/值?

时间:2018-07-11 05:46:15

标签: angular typescript angular6

我拥有的是一个简单的注册页面,该页面注册用户并将表单数据添加到db中。我要显示的是用户详细信息列表,为此我有一个注册组件和一个列表服务。这是我的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);
    }


}

警告“ alert(this.data)”给了我[对象承诺],所以我的问题是如何从作为promise对象的this.data中获取数据?

我的服务是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 个答案:

答案 0 :(得分:1)

您的问题在您的服务中。

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

您在不使用extractData的情况下调用handleError()函数,这与解决您的问题无关,这只是我要提出的观点。您也根本不需要调用这些函数,因为您要返回承诺。

以下代码应该起作用:

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

您已经在组件内部处理.then()

答案 1 :(得分:0)

尝试一下:

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


}

在服务中使用以下行:

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