[英]angular 2 promise into promise
我是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請求中獲取數據?
我將使用可觀察到的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();
});
}
這樣,您將能夠在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.