Yaroslav  Osetrov
Yaroslav Osetrov

Reputation: 894

Angular2 Dynamic Component Loader with HTTP query

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?

Upvotes: 1

Views: 120

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657416

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.

Upvotes: 2

Related Questions