[英]Why is the parent component able to get Observable type data from Angular service but the parent is unable to pass the data to the child component?
父組件正確顯示數據,但沒有將異步填充的數據發送到子組件
我是Angular的新手,並且正在關注此頁面的文檔: https : //angular.io/guide/component-interaction我能夠使用Angular服務將文件詳細信息異步讀取到父組件中。 當我顯示來自父組件的文件詳細信息時,可以看到文件已正確讀取。 當我使用@Output()變量傳遞數據並使用@Input在子組件中接收數據時,我正在獲取空數據,就好像子組件是同步而非異步接收到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>`
您有2個問題:
首先,不要僅在子組件中的父組件中使用Output()
來將數據發射和事件,例如將子數據與父數據一起使用。
而你錯過了這一行
<app-map [uploadedFileDetails]="uploadedFileDetails"><app-map>
其中[uploadedFileDetails]
是子組件中的@Input
變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.