订阅RxJs zip后,Angular 6返回Observable <car>

时间:2018-09-24 14:11:31

标签: angular rxjs6

我想返回一个Observable<Car>

import { zip, Observable } from 'rxjs';

public createMedia(car: Car, dataUrl: string): Observable<Car> {
    const url = this.carDataService.createCar(car);
    const blob = this.dataUrlToBlob(dataUrl);
    const z = zip(url, blob);
    z.subscribe(val => this.saveData(val));
    return ...???(I want return Observable<Car> from saveData(val))
}

saveData(val): Observable<Car> {
  console.log('saveData => val 0: ' + val[0].id + ' val 1: ' + val[1]);
  return this.mediaDataService.saveBytes(val[0].id, val[1]);
}

const oMedia: Observable<Car> = this.createMedia(media);
oMedia.pipe(
  tap(media => console.log('Media created with id: ' + media.id)),
  map(media => this.setMediaId(step, media))
);

1 个答案:

答案 0 :(得分:2)

zip的结果放入管道并使用flatMap运算符:

import { flatMap } from 'rxjs/operators';
import { zip, Observable } from 'rxjs';

public createMedia(car: Car, dataUrl: string): Observable<Car> {
  const url = this.carDataService.createCar(car);
  const blob = this.dataUrlToBlob(dataUrl);

  return zip(url, blob).pipe(
    flatMap(val => this.saveData(val))
  );
}

别忘了订阅createMedia结果。

oMedia.subscribe(car => console.log('Media created with id: ' + car.id));