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?

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

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.