首页 文章

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

提问于
浏览
1

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

父组件有一些默认值为 '' 的变量,然后在构造函数中更新 . 在那里,vars被分配给URL参数中的字符串(在app_module.ts文件中确定) .

我知道在父组件中正确地更新了值,因为我在该组件中成功使用它们,但是我似乎无法将它们传递给具有更新值的子组件 .

导入的变量具有更新前的值 . 如何确保孩子可以在更新后访问该值?

Parent Component

@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)),
    );
  }
}

Child Component

@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();
    });
  }
}

Parent HTML Template

<div>
A whole bunch of unimportant stuff
</div>

<child [companyId]="companyId"
       [userId]="userId"
       [accountId]="accountId">
</child>

我意识到这可能有异步和vars在构造函数更新值之前导入,但我不确定如何让它等到导入它们之前更新值,或者一旦值得到它再次导入它们更新

2 回答

  • 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
        }
    })
    
  • 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)
      }
    }
    

相关问题