親コンポーネントはデータを正しく表示しますが、非同期に入力されたデータを子コンポーネントに送信していません
私は Angular を初めて使用し、このページのドキュメントに従っています: https://angular.io/guide/component-interaction Angular サービスを使用して、ファイルの詳細を親コンポーネントに非同期的に読み込むことができます。親コンポーネントからファイルの詳細を表示すると、ファイルが正しく読み込まれたことがわかります。@Output() 変数を使用してデータを渡し、@Input を使用して子コンポーネントでデータを受け取ると、子コンポーネントが非同期ではなく同期的に入力を受け取ったかのように、空のデータが取得されます。
サービスは次のとおりです。
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import {inFile} from '../Classes/inFile';
@Injectable({
providedIn: 'root'
})
export class AddFilesService {
inFileObj = new inFile();
inFiles:any = [];
constructor(private http:HttpClient) { }
uploadFiles(event){
const files = event.target.files;
for (let i=0; i<= files.length-1 ; i++){
const file = files[i];
const fileName = file.name;
const reader = new FileReader();
//ASYNCHRONOUS FILE READ
reader.onload = () => {
this.inFileObj.name = fileName;
this.inFileObj.size = file.size;
};
reader.readAsArrayBuffer(file);
}
this.inFiles.push(this.inFileObj);
return of(this.inFiles);
}
}
ファイル入力を受け取り、ファイル名とファイルサイズを表示する親コンポーネントコンポーネントは次のとおりです。
import { Component, OnInit, Output } from '@angular/core';
import {AddFilesService} from '../../services/add-files.service';
@Component({
selector: 'app-input-form',
templateUrl: './input-form.component.html',
styleUrls: ['./input-form.component.css']
})
export class InputFormComponent implements OnInit {
inFiles:any = [];
@Output() uploadedFileDetails:string;
constructor(private addFilesService: AddFilesService) { }
ngOnInit() {
}
fileUpload(event) : void {
this.addFilesService.uploadFiles(event).subscribe(
data => {
//THIS WORKS
this.inFiles = data;
//THIS DOES NOT WORK
this.uploadedFileDetails = data;
},
error =>{
console.log(error);
}
);
}
}
親 HTML テンプレートは次のとおりです。
`<input type="file" (change)="fileUpload($event)" multiple>
<table>
<tbody>
<tr *ngFor = "let inFile of inFiles">
<td>Name from Parent: {{inFile.name}}</td>
<td>Size from Parent: {{inFile.size}}</td>
</tr>
</tbody>
</table>`
親コンポーネントからの出力:
Name from Parent: Test.txt Size from Parent: 57
子コンポーネントは次のとおりです。
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css'],
})
export class MapComponent implements OnInit {
@Input() uploadedFileDetails:string;
constructor() {}
ngOnInit() {
}
}
出力のない子 HTML は次のとおりです。
`<table>
<tbody>
<tr *ngFor = "let inFile of uploadedFileDetails">
<td>Name from Child: {{inFile.name}}</td>
<td>Size from Child: {{inFile.size}}</td>
</tr>
</tbody>
</table>`