【问题标题】:RxJS - Observable.map generate objects with asynchronous initilatizationRxJS - Observable.map 生成具有异步初始化的对象
【发布时间】:2017-07-06 11:58:03
【问题描述】:
return this.http.get(url)
.map((response:Response) => {
  return (<any>response.json()).map(actu => new Actualite(actu));      
});

从这个例子。 'Actualite' 构造函数异步生成其属性之一的值(从 url 加载图像并将其操作到画布)

export class Actualite {
Credit: string;
Mini: string;
/* ... */


constructor(fichier:any) {
    this.Credit =       fichier.Credit || '';
    this.Mini =         fichier.Mini || '';
    /* ... */


    if(this.Mini) {
        let img:HTMLImageElement = new Image();
        img.src = this.Mini;

        img.addEventListener('load', ()=> {

            let canvas:HTMLCanvasElement = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            let ctx:CanvasRenderingContext2D = canvas.getContext('2d');

            /*....... Image transformation......*/

            this.Data = canvas.toDataURL();


        })
    }
}

}

所以我想在异步对象初始化结束时订阅这个 Observable 第一个代码,而不是像本例中那样,在创建对象时

谢谢

【问题讨论】:

    标签: asynchronous rxjs


    【解决方案1】:

    我建议在 actualite 类中添加对从图像的加载事件创建的 observable 的引用。

    有点像

    constructor(fichier:any) {
        /*...*/
        this.loadObservable = Rx.Observable.empty() // case where `Mini` is false
        // you can also return a Rx.Observable.of(defaultValue) if you need something on the other side
    
        if (this.Mini) {
            let img:HTMLImageElement = new Image();
            img.src = this.Mini;
    
            this.loadObservable = Rx.Observable
              .fromEvent(img, "load")
              .map(event => /*... do you stuff with the image ...*/)
        }
    }
    

    现在你可以从外部使用这个 observable

    return this.http.get(url)
      .map((response:Response) => {
        return (<any>response.json())
          .map(actu => new Actualite(actu))
          .mergeMap(actu => actu.loadObservable); // this will emit when the loadObservable emits   
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多