[英]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.