[英]What's the pattern to manipulate data in Observables (angular2)
suppose we have this service 假设我们有这项服务
@Injectable()
export class CarService {
constructor (private http: Http) {}
getCars() {
return this.http.get('someurl')
.map(res => <Car[]> res.json())
.catch(this.handleError);
}
}
and we subscribe to this in another component. 我们在另一个组件中对此进行了订阅。 If Car looks like this: 如果Car看起来像这样:
class Car{
Color:string;
Timestamp:any; //this comes as a string in JSON but I want it to be of type Date object
}
and we want to have some logic, ie change date:string to date type, where should this be done? 并且我们希望有一些逻辑,即将date:string更改为date类型,这应该在哪里完成?
in a service? 在服务中? and how? 如何? in a class itself? 在一个班级本身? will .map() hit the constructor of Car class? .map()会影响Car类的构造函数吗?
I would put this process either: 我会把这个过程:
in a map
operator that leverages the map
method of arrays 在利用数组的map
方法的map
运算符中
return this.http.get('someurl') .map(res => <Car[]> res.json()) .map(data => { data.map((d) => { var date = (...) return new Car(color, date); }); return data; }) .catch(this.handleError);
in the constructor of the Car
class 在Car
类的构造函数中
return this.http.get('someurl') .map(res => <Car[]> res.json()) .map(data => { data.map((d) => { return new Car(color, timestampAsString); }); return data; }) .catch(this.handleError);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.