0

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)

3
  • You can create service to store data and use it in any component you want Commented Feb 7, 2018 at 9:18
  • u can share data using services or use redux to create a store for your app Commented Feb 7, 2018 at 9:20
  • please check angular.io/guide/component-interaction Commented Feb 7, 2018 at 9:22

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.