1

我试图通过 HTTP GET 在一个组件中加载数据,然后我需要在动态加载的子组件中使用这些数据。

这是代码:

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

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

在子组件(HeaderComponent)中,我可以this.Account用来获取这些数据。有一个更好的方法吗?

4

1 回答 1

1

您可以只提供祖先组件

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

您提供“服务”的组件可以this.dcl.loadIntoLocation(...)是实际执行的组件,也可以是链上更远的其他祖先组件。

于 2016-04-22T16:27:04.687 回答