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. (Also i must say it, the other component is not a child from the parent view)
-
You can create service to store data and use it in any component you wantPramod Patil– Pramod Patil2018-02-07 09:18:02 +00:00Commented Feb 7, 2018 at 9:18
-
u can share data using services or use redux to create a store for your appFateh Mohamed– Fateh Mohamed2018-02-07 09:20:03 +00:00Commented Feb 7, 2018 at 9:20
-
please check angular.io/guide/component-interactionNour– Nour2018-02-07 09:22:35 +00:00Commented Feb 7, 2018 at 9:22
Add a comment
|
1 Answer
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
2 Comments
Netox
I don't get it in this part: private subject = new Subject<any>();. in new Subject what i should put, the name of the class of my component?
Roland Rácz
@Netox No. It is somekind of 'container' for your data. We're using it in Rxjs. You can put your class in the place of
any, if you want. These links can help you, I think: angularfirebase.com/lessons/… jasonwatmore.com/post/2016/12/01/… In the first example, BehaviorSubject is a special type of Subject. You can read about Subject here: github.com/ReactiveX/rxjs/blob/master/doc/subject.md