【发布时间】:2020-01-09 21:25:14
【问题描述】:
父组件正确显示数据,但没有将异步填充的数据发送到子组件
我是 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>`
【问题讨论】:
-
你把
<app-map [uploadedFileDetails]="uploadedFileDetails"><app-map>放在你的父html中的什么地方?
标签: angular