[英]angular 2 promise into promise
I'm new with Angular 2. I have situation when one promise into another, I have error messages working with http.post into following code. 我是Angular 2的新手。我遇到一种情况,当一个承诺向另一个承诺时,我在使用http.post的错误消息进入以下代码。 How should I use 我应该怎么用
.then 。然后
here? 这里?
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
});
});
});
}
}
How should I get data from POST request? 我应该如何从POST请求中获取数据?
I would refactor your code using the toPromise
method of observable this way: 我将使用可观察到的toPromise
方法来重构您的代码, 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();
});
}
This way you will be able to call the then
method on it within the getComponentData
method: 这样,您将能够在getComponentData
方法中对其调用then
方法:
getComponentData(): Promise<IComponentData> {
return this.postData().then((data) => {
return {
title: data.title,
signInUrl: data.signInUrl,
orgFriendlyName: data.orgFriendlyName
};
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.