angular2子组件如何导入由父组件更新的var

时间:2018-07-05 01:46:02

标签: angular

我有两个组件,每个组件都需要为服务器调用使用相同的URL参数。

父组件具有一些默认值为''的var,然后在构造函数中对其进行更新。在那里,变量是通过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>

我意识到这可能需要做一些异步操作,并且在构造函数更新值之前先导入var,但是我不确定如何等到值更新后再导入它们,或者让它再次导入一次值会更新

2 个答案:

答案 0 :(得分: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
    }
})

答案 1 :(得分:0)

您可以在“ 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)
  }
}