0
沿着Angular 2教程。我試圖將以下方法從promises
轉換爲observables
。我的嘗試如下。角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);
}
}