遵循Angular 2教程。我正在尝试将以下方法从promises
转换为observables
。我的尝试如下。
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);
}
}
答案 0 :(得分:1)
1)转换是否正确?
转换似乎不正确。通过将function
引用传递给可观察的回调,您将失去this
上下文。您必须使用Arrow function
与this
&amp;明确地调用函数。
// Observable
getGroups(): Observable<Group[]> {
return this.http.get(this.groupsUrl)
.map(this.extractData) //don't pass function reference
.catch(this.handleError);
}
应该是
// Observable
getGroups(): Observable<Group[]> {
return this.http.get(this.groupsUrl)
//.map(this.extractData.bind()) //this would work but its bad pattern
.map(()=> this.extractData())
.catch(this.handleError);
}
如果你在代码中的某个地方做了同样的事情,那么对其他函数也要做同样的事情。
2)我如何转换getGroup()方法
它将如下所示
getGroup(id: number): Promise<Group> {
return this.getGroups()
.map(groups => groups.find(group => group.id === id));
}