【问题标题】:angular2 Child Component how to import var updated by Parent Componentangular2子组件如何导入由父组件更新的var
【发布时间】: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>

我意识到这可能有一些异步操作,并且在构造函数更新值之前导入了变量,但我不确定如何让它等到值更新后再导入它们,或者让它再次导入它们一次值得到更新

【问题讨论】:

  • 我看不到您实际在哪里设置 companyIduserIdaccountId 的值
  • @Brian C,您必须等于父组件中的变量 this.companyId、this.userId 和 this.accountId(不需要再做任何事情,忘记 ngAfterViewInit)

标签: angular


【解决方案1】:

这是因为您没有将值分配给组件变量。

现在,您正在 map 函数中动态创建一个对象,并将其作为返回值从 map 传递到 concat map。这就是您的服务获得输入的原因。要将其分配给组件变量,您必须使用 **"this.VARIABLE_NAME"**

你可以这样做:

map(params => {
    this.companyId = params['company_id'],
    this.userId = params['user_id']
    this.accountId = params['account_id']
    // You can either return in below fashion or you can use the component variables directly in the concatMap like this.companyId etc... 
    // because you assigned the values to such variables above.
    return {
        companyId: this.companyId,
        userId: this.userId,
        accountId: this.accountId
    }
})

【讨论】:

  • 谢谢!我需要对您的建议进行一些更改(并编辑您的答案以反映这一点),但这有效!我没有意识到我只是将 url 参数应用于服务,而不是实际的组件变量!
【解决方案2】:

您可以在“ngOnChanges”生命周期挂钩中访问更新的绑定。可能有错别字:)。见下文。

export class Child implements OnChanges {

  /* IMPORTED VARS HERE SHOULD HAVE VALUE FROM URL PARAMS*/
  @Input() companyId: string;
  @Input() userId: string;
  @Input() accountId: string;

  ngOnChanges(changes: SimpleChanges){
    console.log("This prints blank strings")
    console.log(changes.primaryId.currentValue)
    console.log(changes.userId.currentValue)
    console.log(changes.accountId.currentValue)
  }
}

【讨论】:

  • Hmm.. 刚刚尝试过,结果完全相同(Parent 中的初始化值显示在 Child 组件的控制台日志中,然后传递给服务器,而不是 URL 参数)
猜你喜欢
  • 2016-12-02
  • 2016-07-24
  • 2016-09-04
  • 2021-07-04
  • 1970-01-01
  • 2018-04-18
  • 2017-07-10
  • 2020-08-08
  • 2017-05-03
相关资源
最近更新 更多