2016-03-23 11 views
0

私はAngular 2で新しくなりました。別の約束をすると、次のコードにhttp.postを使ってエラーメッセージが出ます。どのように私はangular 2 promiseに約束します

.thenここ

を使用する必要がありますか?

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

私は、観察の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 
    }; 
    }); 
} 
関連する問題