嗨,我仍在尝试RxJS,我正在尝试数组中的每个Observable来检索该Observable的链接图像,如下所示:
到目前为止,我已经做到了:
public collectAssignements(): Observable<Observable<AssignementEntity>> {
return this.assignementService.get('').pipe(
map((assignments: AssignementEntity[]) => from(assignments.map((assignment) => new AssignementEntity(assignment))))
);
}
public assignements(): Observable<AssignementEntity[]> {
return this.collectAssignements().pipe(
mergeMap((assignment: Observable<AssignementEntity>) => {
return assignment;
}),
map((assignment: AssignementEntity) => {
return assignment;
}),
// here I'd like to use my function getPhoto on assignment.Platform.Logo if there is one (Logo is an Id)
// then set the retreived string (dataUrl) to assignment.Platform.Image
// but I can't figure out how to do that?
toArray()
)
}
要从我的任务中获取我的图像,我必须将照片ID(在这里,assignment.Platform.Logo)传递到getPhoto
中,这里返回一个可观察的字符串:
public fileReader(blob: Blob): Observable<string> { // @todo inclure le FileReaderService readAsDataURL
return Observable.create((obs: Observer<string | ArrayBuffer>) => {
const reader = new FileReader();
reader.onerror = err => obs.error(err);
reader.onabort = err => obs.error(err);
reader.onload = () => obs.next(reader.result);
reader.onloadend = () => obs.complete();
return reader.readAsDataURL(blob);
});
}
public getPhoto(id: string, size: string = "min"): Observable<string> {
return this.httpClient.get(`${this.environment.get('webServiceUrl')}/photos/${id}/${this.endpoint.slice(0, -1)}/${size}`, { responseType: "blob" as "json" }).pipe(
mergeMap((blob: Blob) => this.fileReader(blob))
);
}
获取assignmentService
返回一个Observable<Assignment[]>
,而AssignmentEntity
具有一个Platform
属性的Logo
(实体)(它是一个带有字符串的ID )。此外,Platform
实体的Image
属性(字符串)默认为空,等待填充dataUrl
。
答案 0 :(得分:1)
在处理RxJS文档后,我想出了以下解决方案:
public assignements(): Observable<AssignementEntity[]> {
return this.assignementService.get('').pipe(
map((assignments: AssignementEntity[]) => from(assignments.map((assignment) => new AssignementEntity(assignment)))),
mergeMap((assignment: Observable<AssignementEntity>) => {
return assignment;
}),
map((assignment: AssignementEntity) => {
return assignment;
}),
mergeMap((assignment: AssignementEntity) => { // forEach assignment if it has a Logo then make a request to get the image
return assignment.Platform.Logo !== null ? this.platformService.getPhoto(assignment.PlatformId).pipe(
map((image: string) => {
assignment.Platform.Image = image;
return assignment;
})
) : of(assignment); // return the base assignment if no logo
}),
toArray(), // convert to an array
);
}