角度2承诺承诺

时间:2016-03-23 15:24:15

标签: typescript angular

我是Angular 2的新手。我有一种情况,当一个承诺到另一个,我有使用http.post的错误消息到下面的代码。我应该如何使用

  

。然后

这里吗?

export class KeyValue {
    constructor(
        private OrganizationId: string,
        private OrganizationFriendlyName: string) {
    }
}

export interface IComponentData {
    title: string;
    signInUrl: string;
    orgFriendlyName: KeyValue[];
}

@Injectable()
export class Api {
    title: string = '<Application Name>';
    signInUrl: string = '';
    http: Http;
    orgFriendlyName: KeyValue[];

    postData(): Promise<KeyValue[]> {
        var headers = new Headers();
        headers.append('Content-Type', 'application/json'); 

        return this.http.post('url', JSON.stringify({}), { headers: headers })
            .then(function(res) {
            .map(res => res.json());
            .subscribe((res: KeyValue[]) => this.orgFriendlyName = res);
        });

    }

    getComponentData(): Promise<IComponentData> {
        return this.postData().then(() => {
            return new Promise((resolve, reject) => {
                resolve({
                    title: this.title,
                    signInUrl: this.signInUrl,
                    orgFriendlyName: this.orgFriendlyName
                });
            });
        });
    }
}

我应该如何从POST请求中获取数据?

1 个答案:

答案 0 :(得分:1)

我会使用toPromise方法以这种方式重构您的代码:

postData(): Promise<KeyValue[]> {
  var headers = new Headers();
  headers.append('Content-Type', 'application/json'); 

  return this.http.post('url', JSON.stringify({}), { headers: headers })
      .map(res => res.json())
      .toPromise();
  });
}

这样您就可以在then方法中调用getComponentData方法:

getComponentData(): Promise<IComponentData> {
  return this.postData().then((data) => {
    return {
      title: data.title,
      signInUrl: data.signInUrl,
      orgFriendlyName: data.orgFriendlyName
    };
  });
}