[英]Converting rxjs 5 map to rxjs 6 map
Consider the following code Angular 5 + older rxjs 考虑以下代码Angular 5 +较旧的rxjs
this.measurementUnitsService.GetAll().subscribe(
res => {
this.measurementUnits = res.map(x => new MeasurementUnit(x));
}
)
I am getting a list of objects and for each one of them creating a new strongly typed class. 我正在获取对象列表,并为每个对象创建一个新的强类型类。
How would I go about doing the same in angular 6 + rxjs 6 My attempt. 我将如何在angular 6 + rxjs 6中做同样的事情。
this.measurementUnitsService.GetAll().pipe<MeasurementUnit[]>(mergeMap(x => new MeasurementUnit(x))).subscribe(
res => {
this.measurementUnits = res;
}
)
It generates an error unfortunately Type 'MeasurementUnit[]' has no properties in common with type 'Partial<MeasurementUnit>'.
不幸的是,它生成错误,
Type 'MeasurementUnit[]' has no properties in common with type 'Partial<MeasurementUnit>'.
MeasurementUnit
just in case MeasurementUnit
以防万一
export class MeasurementUnit {
Id: number;
CreatedDate: Date;
ModifiedDate: Date;
Disabled: boolean;
DisabledDate: Date;
Name: string;
Description: string;
ParentId: number;
public constructor(item: Partial<MeasurementUnit>) {
//item.EstablishedDate = new DatePipe('en-US').transform(item.EstablishedDate, "yyyy-MM-dd");
Object.assign(this, item);
}
}
You have an Observable<MeasurementUnit[]>
not an Observable<MeasurementUnit>
. 您有一个
Observable<MeasurementUnit[]>
而不是Observable<MeasurementUnit>
。
This means, that when the observable emits a value it will be an array not a single value. 这意味着,当可观察对象发出一个值时,它将是一个数组而不是单个值。 Hence, you need the normal
array
map, not the Observable
one. 因此,您需要普通的
array
映射,而不是Observable
array
映射。
Just do: 做就是了:
this.measurementUnitsService.GetAll()
.pipe(
map(array => array.map(x => new MeasurementUnit(x)))
).subscribe(res => this.measurementUnits = res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.