return this.http.get(url)
.map((response:Response) => {
return (<any>response.json()).map(actu => new Actualite(actu));
});
从这个例子。 &#39; Actualite&#39;构造函数异步生成其中一个属性的值(从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第一个代码,而不是像本例中那样创建对象时
由于
答案 0 :(得分:0)
我建议添加对actualite
类中图像的加载事件创建的可观察对象的引用。
像
这样的东西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
});