2016-09-30 12 views
2

私は検証後にいくつかの画像情報をテンプレートに送信しようとしています。しかし、私は取得していません。角2 - テンプレートに非同期情報を送信する方法

テンプレートに移動する変数はコールバック内にあるか、非同期関数内にあり、この情報をテンプレートに送信することはわかりません。

この問題を解決するのに役立つでしょうか?私はすべてを試しました。

event.component.ts

import "rxjs/Rx"; 
import {Component} from '@angular/core'; 

@Component({ 
    selector: '<my-image></my-image>', 
    templateUrl: './event.component.html',  
}) 
export class EventComponent { 
    files: File[]; 
    file: any 
    imageName: any; 
    imageSize: any; 
    whithImage = false; 

    ngOnInit() {this.files = []} 

    onFileSelect(event) { 
     this.files = event.dataTransfer ? event.dataTransfer.files : event.target.files; 
     this.file = this.files[0]; 
     this.isImage(this.file, function(res, file){ 
      if(res==true){ 
       this.imageName = file.name; 
       this.imageSize = file.size; 
       this.whithImage = res; 
      } 
     }) 
    } 

    isImage(file, callback) { 
     var reader = new FileReader(); 
     reader.onload = function(event) { 
      var contents = reader.result; 
      var buf = new Uint8Array(contents); 
      if(buf[0] === 0xFF && buf[1] === 0xD8 && buf[2] === 0xFF){ 
       callback(true, file) //jpg 
      }else{callback(false)} 
     }; 
     reader.readAsArrayBuffer(file); 
    } 

    onChooseClick(event, fileInput) { 
     fileInput.value = null; 
    } 

event.component.html

<span (click)="onChooseClick($event, fileinput)"> 
    Image<input #fileinput type="file" (change)="onFileSelect($event)"/> 
</button> 
<div *ngIf="whithImage"> 
    <p>{{ imageName }}</p> 
    <p>{{ imageSize }}</p> 
</div> 

答えて

3

arrow functionを使用することにより、適切thisコンテキストを使用し、@peeskillet、すなわち–最初に示唆したものを試してみてください:

export class EventComponent { 
    onFileSelect(event) { 
     ... 
     this.isImage(this.file, (res, file) => {  // <---- 
      if(res==true) { 
       this.imageName = file.name; 
       this.imageSize = file.size; 
       this.whithImage = res; 
      } 
     }); 
    } 

これがうまくいかない場合、Angularは非同期イベントをモンキーパッチする方法を知らないため、イベントが発生すると角度変化の検出は実行されません(ビューは新しいコンポーネントのプロパティ値)。 manually trigger change detectionにする必要があります。ここではそれを行うための一つの方法です:

import {ChangeDetectorRef} from '@angular/core';  // <----- 
export class EventComponent { 
    constructor(private cdref:ChangeDetectorRef) {} // <----- 
    onFileSelect(event) { 
     ... 
     this.isImage(this.file, (res, file) => {  // <---- 
      if(res==true) { 
       this.imageName = file.name; 
       this.imageSize = file.size; 
       this.whithImage = res; 
       this.cdref.detectChanges();   // <------ 
      } 
     }); 
    } 
+2

がより問題のように見えるが、function' 'を使用すると、' this' ;-) –

+0

は、彼の貢献のためにあなたにマークをありがとう、それでも機能のコメントがされ 'imagenameの、IMAGESIZEとwhithImage'だけを残し、 'this.cdref.detectChanges();だけを残しておけば、次のエラーが表示されます: '未定義のcdref'を読み取れません。 –

+0

@peeskillet、thanks、updated。 –

関連する問題