[英]Output of data from one component in the other component . Angular 5
我需要幫助。 我有1個父組件。 里面有五個孩子。 這是一張含卡片的頁面。 每個卡都是一個組件。 在一張卡中,我將一個csv文件上傳到服務器,服務器立即為我提供json,我需要在其他卡中以表格,圖形的形式顯示json,而無需其他get-requests請求。 實際上,單擊“發送”按鈕后,文件消失了,然后出現在所有組件中。 獲取並通過服務執行我的請求。 我不明白如何通過服務將數據傳輸到所有組件。 先感謝您。
我有簡單的http.service.ts
constructor(private http: HttpClient) { }
getData() {
return this.http.get('http://localhost:8080');
}
postData(data: any) {
return this.http.post('http://localhost:8080', data, {
reportProgress: true,
observe: 'events'
})
}
}
和子組件,將文件上傳到服務器
export class SignalsComponent {
selectedFile: File = null;
addFileStatus = false;
progressBar: any;
signalsFiles: any;
constructor(private http: HttpService) {}
onFileSelected(event) {
this.selectedFile = <File>event.target.files[0];
this.addFileStatus = true;
}
sendCsvFile() {
const formData = new FormData();
formData.append('csv-file', this.selectedFile, this.selectedFile.name);
this.http.postData(formData)
.subscribe(event => {
if(event.type === HttpEventType.UploadProgress) {
this.progressBar = 'Upload Progress: ' + Math.round(event.loaded / event.total * 100) + '%';
} else if (event.type === HttpEventType.Response) {
this.signalsFiles = event.body;
console.log(this.signalsFiles);
}
});
}
您可以做的就是在您的服務中創建一個可觀察的對象。 發出HTTP請求時,您可以通過Observable發送該響應,以便任何訂閱者都將得到通知。 該服務將如下所示:
import { Injectable } from '@angular/core';
import { Subject } from "rxjs/Subject";
import { HttpClient } from "@angular/common/http";
@Injectable()
export class ExampleService {
private _dataChanged = new Subject<any>();
// Components can subscribe to this
public onDataChanged = this._dataChanged.asObservable()
constructor(private http: HttpClient) {
}
public loadData() {
// Emit the data here
return this.http.get("https://jsonplaceholder.typicode.com/posts/1")
.subscribe((data) => this._dataChanged.next(data));
}
}
您的組件可以訂閱可觀察的onDataChanged,如下所示:
constructor(private service: ExampleService) {
this.service.onDataChanged.subscribe((data) => this.data = data);
}
一旦您的組件之一調用loadData()
,就會向所有訂閱者通知結果。
這是一個stackblitz示例https://stackblitz.com/edit/angular-gueraq?file=app%2Fhello.component.ts
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.