【发布时间】:2018-07-05 01:46:01
【问题描述】:
我有两个组件,每个组件都需要使用相同的 URL 参数进行服务器调用。
父组件有一些默认值为'' 的变量,然后在构造函数中更新。在那里,变量被分配给来自 URL 参数的字符串(在 app_module.ts 文件中确定)。
我知道父组件中的值正在正确更新,因为我在该组件中成功使用了它们,但是我似乎无法将它们传递给具有更新值的子组件。
导入的变量具有更新前的值。如何确保孩子可以在更新后访问该值?
父组件
@Component({
selector: 'parent',
templateUrl: './parent.ng.html',
})
export class Parent<T> {
/** Response protobuf from the partner details service. */
response: Observable<ParentServiceResponse>;
/** THESE VALUES NEED TO BE ACCESSED BY CHILD */
companyId = '';
userId = '';
accountId = '';
/** VARS ARE UPDATED HERE BASED ON URL PARAMETERS */
constructor(
route: ActivatedRoute,
private readonly parentServiceResponse: ParentServiceResponse) {
this.response = route.params.pipe(
map(params => ({
companyId: params['company_id'],
userId: params['user_id'],
accountId: params['account_id'],
})),
concatMap(
ids => this.parentServiceResponse.getResponse(
ids.companyId, ids.userId, ids.accountId)),
);
}
}
子组件
@Component({
selector: 'child',
templateUrl: './child.html',
})
export class Child implements AfterViewInit{
/* IMPORTED VARS HERE SHOULD HAVE VALUE FROM URL PARAMS*/
@Input() companyId: string;
@Input() userId: string;
@Input() accountId: string;
ngAfterViewInit(){
console.log("This prints blank strings")
console.log(this.companyId)
console.log(this.userId)
console.log(this.accountId)
// Call function which subscribes to Observable, using the imported vars
this.data.pageIndex.subscribe(x => {
this.queryAndAppendData();
});
}
}
父 HTML 模板
<div>
A whole bunch of unimportant stuff
</div>
<child [companyId]="companyId"
[userId]="userId"
[accountId]="accountId">
</child>
我意识到这可能有一些异步操作,并且在构造函数更新值之前导入了变量,但我不确定如何让它等到值更新后再导入它们,或者让它再次导入它们一次值得到更新
【问题讨论】:
-
我看不到您实际在哪里设置
companyId、userId、accountId的值 -
@Brian C,您必须等于父组件中的变量 this.companyId、this.userId 和 this.accountId(不需要再做任何事情,忘记 ngAfterViewInit)
标签: angular