0
Angular 2 튜토리얼을 따라하십시오. 다음 방법을 promises
에서 observables
으로 변환하려고합니다. 나의 시도는 아래에있다.angular 2 관측 가능 약속
1) 변환이 정확합니까?
2) 어떻게)합니다 (getGroup()
방법을
기능 getgroups()
// Promise
getGroups(): Promise<Group[]> {
return this.http.get(this.groupsUrl)
.toPromise()
.then(response => response.json().data as Group[])
.catch(this.handleError);
}
// Observable
getGroups(): Observable<Group[]> {
return this.http.get(this.groupsUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(response: Response) {
let body = response.json();
return body.data || { };
}
getGroup()
// Promise
getGroup(id: number): Promise<Group> {
return this.getGroups()
.then(groups => groups.find(group => group.id === id));
}
// Observable
// ================
// HOW?
// ================
이 createGroup()
// Promise
createGroup(name: string): Promise<Group> {
return this.http
.post(this.groupsUrl, JSON.stringify({name: name}), {headers: this.headers})
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
}
// Observable
createGroup(name: string): Observable<Group> {
return this.http
.post(this.groupsUrl, JSON.stringify({name: name}), {headers: this.headers})
.map(res => res.json().data)
.catch(this.handleError);
}
updateGroup을 변환 할 것
// Promise
updateGroup(group: Group): Promise<Group> {
const url = `${this.groupsUrl}/${group.id}`;
return this.http
.put(url, JSON.stringify(group), {headers: this.headers})
.toPromise()
.then(() => group)
.catch(this.handleError);
}
// Observable
updateGroup(group: Group): Observable<Group> {
const url = `${this.groupsUrl}/${group.id}`;
return this.http
.put(url, JSON.stringify(group), {headers: this.headers})
.map(() => group)
.catch(this.handleError);
}
deleteGroup는()
// Promise
deleteGroup(id: number): Promise<void> {
const url = `${this.groupsUrl}/${id}`;
return this.http
.delete(url, {headers: this.headers})
.toPromise()
.then(() => null)
.catch(this.handleError);
}
// Observable
deleteGroup(id: number): Observable<void> {
const url = `${this.groupsUrl}/${id}`;
return this.http
.delete(url, {headers: this.headers})
.map(() => null)
.catch(this.handleError);
}
}