1

I'm trying to load data via HTTP GET in one component and then I need to use this data in child component that loaded dynamically.

Here's the code:

ngOnInit(){
this.accountService.getPersonalInfo().subscribe(
        response => {
            this.Account = response.json();

            this.dcl.loadIntoLocation(HeaderComponent, this.elementRef, 'header')
                .then(compRef => {
                        compRef.instance.Account=this.Account;
                    }
                );
        }
        );
}

In child component (HeaderComponent) I can use this.Account to get this data. Is there a better way to do this?

1 Answer 1

2

You can just provide in an ancestor component

@Component({
  selector: 'header-cmp',
  ...
})
class HeaderCmp {
  constructor(private account:AccountService) {
    this.account.someObservable.subscribe(...); // or whatever
  }
}

@Component({
  selector: 'parent-cmp',
  providers: [AccountService],
  ...
})
class ParentCmp {
  constructor(private account:AccountService) {
    // set some values
  }
}

The component where you provide the "service" can be the component where this.dcl.loadIntoLocation(...) is actually executed or some other ancestor component further up the chain.

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

2 Comments

But then it will be two similar http queries - one in the parent component and other in the child, right? I need to use the data (this.Account) in both components
Angulars DI maintains a single instance per provider. The ParentCmp will get the instance of the provider on itself. For the HeaderCmp DI will look upwards until it finds a provider for AccountService. If you don't add it anywhere in between (only applicable if ParentCmp and HeaderCmp are not in a direct parent-child relation) then DI will find the provider of ParentCmp and pass it to HeaderCmp as well. This way both components get a reference to the same AccountService instance.

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.