角度2可观察到可观察[] [英] Angular 2 Observable to Observable []
问题描述
不确定标题是否准确,不确定确切的术语.
Not sure if the title is accurate as not sure of the exact terminology.
假设我有一些类似下面的代码.
Suppose I have some code like the the below.
当我使用第一种方法加载单个资源时,我可以创建一个丰富模型类的实例,该类在传递给map(...)的函数中包装/修饰普通的JS对象.
When I load an individual resource using the first method I can create an instance of a rich model class which wraps/decorates the plain JS object in the function passed to map(...).
在第二种方法中,如果响应是一个Course对象数组,如何实现相同的目的?
How can I achieve same in the second method where the response is an array of Course objects?
@Injectable()
export class CourseService {
constructor(private restangular: Restangular) {
}
public getCourse(id: number): Observable<any> {
return this.restangular.one("courses", id).get().map(response =>
new Course(response)
);
}
public getAllCourses(): Observable<any> {
return this.restangular.all("courses").getList().map(response => {
//an array of courses
console.log(response);
});
}
}
推荐答案
由于第二种方法接收到数组,因此可以使用 Array.map()
迭代数组的值并进行转换每个值进入 Course
实例:
Since the second method receives an array, you can use Array.map()
to iterate on the values of the array and convert each value into a Course
instance:
public getAllCourses(): Observable<any> {
return this.restangular.all("courses").getList().map(response => {
return response.map(courseData => new Course(courseData));
});
}
此代码可能会令人困惑,因为:
This code can be confusing because:
- 第一个
.map()
是 Observable.map()(来自RxJS库). - 第二个
.map()
是 Array.map()(普通JavaScript).
- The 1st
.map()
is Observable.map() (from RxJS library). - The 2nd
.map()
is Array.map() (plain JavaScript).
为简便起见,您可以将方法主体写在一行上(这样就避免了内部的 return
):
For brevity, you could write the method body on a single line (thus avoiding the inner return
):
public getAllCourses(): Observable<any> {
return this.restangular.all("courses").getList().map(response => response.map(courseData => new Course(courseData)));
}
但是它有点难读.:)
这篇关于角度2可观察到可观察[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!