2016-03-23 21 views
0

Ich bin neu mit Angular 2. Ich habe Situation, wenn ein Versprechen in ein anderes, habe ich Fehlermeldungen mit http.post in folgenden Code arbeiten. Wie soll icheckig 2 Versprechen in Versprechen

.then

hier?

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

Wie soll ich Daten von POST-Anfrage bekommen?

Antwort

1

Ich würde Ihr Code mit dem toPromise Methode beobachtbarer diese Weise Refactoring:

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

Auf diese Weise können Sie die then Methode auf sie innerhalb des getComponentData Methode aufzurufen:

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