1

I am using angular 6. I want to send data (which I am getting from external API) from app.component to other (child) components, I do not want to call that common API/Service in all components separately and repetitively. I want to call it once, so that's why I am calling in app.component.ts

Here is a service/API code

this.mainService.getBaseModel().subscribe(ret => {
        this.basemodel = ret;
    }, error => { }, () => {
});

I want to send this 'basemodel' value across all components in my app. Help me to resolve and understand it better. Thank you.

3 Answers 3

3

There are two ways to achieve this,

  1. @Input, with this we can pass the data to every child component from parent component.
  2. Create a common Service for all these and then use service methods to get the Object

If you have one or two to components to share data from Parent then use @Input otherwise Service with latest RxJs classes(BehaviourSubject, Subject, etc..) could be really easy.

if you want to follow @Input then follow this post - pass @input data to child

follow this for Service with BehaviourSubject - https://medium.com/@weswhite/angular-behaviorsubject-service-60485ef064fc

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

Comments

0

Without knowing the structure of you app it's hard to say which approach to use. You could use:

  • combinations of @Input() and @Output()
  • another service to save and distribute the data
  • a store like ngrx

Comments

0

In official Angular documentation you can find several approaches to this. They can be found here: https://angular.io/guide/component-interaction#pass-data-from-parent-to-child-with-input-binding

There are also live examples for the above methods here: https://stackblitz.com/angular/plpgkjondrl

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.