[英]Angular 5 - Passing data to another component
I have this form which through an API service i can get data from a specific user so i want to send that data to another component and then extract it using *ngFor, but i really don't have any clue about how to do it. 我有这种形式,可以通过API服务从特定用户那里获取数据,因此我想将该数据发送到另一个组件,然后使用* ngFor提取它,但是我真的不知道如何做。 (Also i must say it, the other component is not a child from the parent view)
(我也必须这样说,从父视图来看,其他组件不是孩子)
Use a service: 使用服务:
@Injectable()
export class DataService {
private subject = new Subject<any>();
setData(message: string) {
// just an example:
this.subject.next({ text: message });
}
getData(): Observable<any> {
return this.subject.asObservable();
}
}
In your parent component: 在您的父组件中:
this.dataService.setData(something);
In your other component you can subscribe: 在您的其他组件中,您可以订阅:
this.dataService.getData().subscribe(data => {
// do stuff with the data, for example:
this.myData = data;
);
Don't forget the constructor in your components: 不要忘记组件中的构造函数:
constructor(private dataService: DataService) {}
An other solution could be to use Ngrx: https://github.com/ngrx/platform 另一个解决方案可能是使用Ngrx: https : //github.com/ngrx/platform
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.