2017-08-17 5 views
0

私は以下の設定を使ってangular2の画像ファイルを読み込みます。私はinput要素を使用して、ファイルを選択するウィンドウを表示し、ファイルが選択されたときにaddThumbnail関数をトリガーします。 inputのクリックが別のボタンによってトリガーされています。私は、addThumbnailのトリガが時々静かに失敗することに気付きました。つまり、ファイルを選択しても機能が起動しなくなってしまいました。これは5回中1回発生する可能性があるかどうかわかりません。私はaddThumbnailの中にブレークポイントを設定することでこれをデバッグしようとしましたが、それは起動されていません。angular2 filereaderが不思議に失敗します

<div class="extra-image-container"> 
    <input type="file" accept="image/*" (change)="addThumbnail($event)" style="display:none;" #fileInput2/> 
    <div class="thumbnail-button" (click)="fileInput2.click()"> 
     <span><i class="material-icons">photo_camera</i></span><br> 
     <span>Extra Images</span> 
    </div> 
</div> 

これは私が使用しているaddThumbnail関数とファイルリーダー関数です。

addThumbnail(event) { 
    console.log('adding thumbnail'); 
    var subscription = this.readImage(event.target).subscribe((result) => { 
     this.thumbnails.push(result.imageUrl); 
     this.editedThumbnails.push(result.imageUrl); 
     subscription.unsubscribe() 
    }); 
} 

readImage(inputValue: any) : Observable<any> { 
    var file:File = inputValue.files[0]; 
    var myReader:FileReader = new FileReader(); 
    var observable = new Observable(observer => { 
     myReader.onloadend = (e) => { 
      observer.next({imageUrl: myReader.result}); 
      console.log("image loaded"); 
      // var image = new Image(); 
      // image.addEventListener("load",() => { 
      //  observer.next({ 
      //   imageWidth: image.width, 
      //   imageHeight: image.height, 
      //   imageSize: file.size/1000, 
      //   imageUrl: myReader.result 
      //  }) 
      //  console.log("image loaded"); 
      // }) 
      // image.src = myReader.result; 
     } 
     myReader.readAsDataURL(file);//triggers the callback 
    }) 
    return observable 
} 
+0

あなたのコードが正しく)(subscription.unsubscribe 'ところで、クロム60に取り組んでいる – slesh

+0

ログを見ていいだろう;'役に立たないようです。 –

+0

@ルドビッチギョームメントは試行錯誤の一部でしたが、指摘に感謝します。 – quantdaddy

答えて

0

それはあなたが同じファイルを次々に読めば、ファイルが同じであるため、その後、changeがトリガされていないことが判明。だから、これを修正するには、ファイルがロードされた後にinput要素の値を空の文字列に設定しなければなりませんでした。

@ViewChild('fileInput2') private thumbImageInput: ElementRef; 
// and in the addThumbnail method: 
addThumbnail(event) { 
    var subscription = this.readImage2(event.target).subscribe((result) => { 
     this.thumbnails.push(result.imageUrl); 
     this.editedThumbnails.push(result.imageUrl); 
     window.URL.revokeObjectURL(result.imageUrl); 
     this.thumbImageInput.nativeElement.value = ''; 
    }); 
} 
関連する問題