我正在使用服務在服務器上上傳圖像。這裏是:Angular 2&Vanilla JS:在進行http調用之前等待圖像加載
addPictures(files: File[], folder: string): Observable<Parse.Object[]> {
let hasError = false;
for (let file of files) {
let [type, ext] = file.type.split('/');
if (type.toLowerCase() !== 'image' || !environment.imgExts.includes(ext.toLowerCase())) { hasError = true; }
}
if (hasError) { return Observable.throw('Invalid extension detected'); }
let observables: Observable<Parse.Object>[] = [];
for (let file of files) {
// Get its size
let img = new Image();
img.onload =() => {
// Create the Parse document
let parseImg = { url: '', type: file.type, width: img.width, height: img.height };
// Upload it on Amazon and add it to DB
observables.push(this.addPicture(parseImg, file, folder));
console.log('pushing to array');
}
img.src = window.URL.createObjectURL(file);
}
console.log('forkjoin');
return Observable.forkJoin(observables);
}
所有的功能都很好。我面臨的問題是,當我使用img.onload
時,forkJoin
不會在發射前等待它。我想要的是等待所有的圖像加載,然後觸發thr forkJoin發送它們全部。
我已經嘗試了一個條件(當最後一項被推入數組,觸發forkJoin),但是問題是我的組件按照Cannot read property 'subscribe' of undefined
的順序返回錯誤。這裏
編輯是我的蘇氨酸fromEvent代碼:
addPictures(files: File[], folder: string): Observable<Parse.Object[]> {
let hasError = false;
for (let file of files) {
let [type, ext] = file.type.split('/');
if (type.toLowerCase() !== 'image' || !environment.imgExts.includes(ext.toLowerCase())) { hasError = true; }
}
if (hasError) { return Observable.throw('Invalid extension detected'); }
let observables: Observable<Parse.Object>[] = [];
for (let file of files) {
// Get its size
let img = this.fromImgEvent(file, window.URL.createObjectURL(file), folder);
observables.push(img);
}
console.log('forkjoin');
return Observable.forkJoin(observables);
}
fromImgEvent(file: File, url: string, folder: string) {
return Observable.create(observer => {
let img = new Image();
img.onload =() => {
// Create the Parse document
let parseImg = { url: '', type: file.type, width: img.width, height: img.height };
// Upload it on Amazon and add it to DB
observer.next(this.addPicture(parseImg, file, folder));
observer.complete();
}
img.src = url;
});
}
你有沒有嘗試'Observable.fromEvent'操作符來監聽onload ev作爲可觀察的。 – cyrix
不,我不知道這個,你能舉個快速的例子嗎? – trichetriche