简体   繁体   English

如何获取子组件angular2中的最新数据

[英]How to get the latest data in child component angular2

I need to keep the data updated in a child component to do some maths我需要在子组件中更新数据以进行一些数学运算

I have my parent component:我有我的父组件:

@Component({
  selector: 'car-brand-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.scss'],
  providers: [CarBrandService, Response, SessionService, ServerService,     ListTableComponent, TableAction, Table, TableRow, TableRowField]
})
export class CarBrandIndexComponent implements OnInit {
  table = new Table();

  constructor(private mainService : CarBrandService) {
    this.refresh(this.table.page,this.table.size);
}

 refresh(pageNumber : number, pageSize : number){
   this.mainService.get(pageNumber, pageSize).then(result => {

     this.table.total = result.data.total;
   });
 }

And in the view I have:在我看来:

 <list-table [info]="table" (updateTable)="updateTable($event)"></list-table>

So i'm sending the var table to the component list-table所以我将 var 表发送到组件列表表

And in my child component I have在我的子组件中,我有

@Component({
  selector: 'list-table',
  templateUrl: './list-table.component.html',
  styleUrls: ['./list-table.component.scss'],
  providers: [ListTableService]
})
export class ListTableComponent implements OnInit {
  @Input() 
  info: Table;
  @Output()
  updateTable = new EventEmitter();
  pages : number[] = [];
  constructor(public listTableService : ListTableService) {
  }

  updateFooter() {
    if(this.info){
      var amountofPages = this.info.total % this.info.size == 0 ? ( this.info.total % this.info.size ) : ( this.info.total % this.info.size ) + 1;
      for(var i = 1; i <= amountofPages; i++){
        this.pages.push(i);
      }
    }
  }

  ngOnInit(){
    this.updateFooter();
  }
}

The issue is that in the line:问题是在这一行:

 var amountofPages = this.info.total % this.info.size == 0 ? ( this.info.total % this.info.size ) : ( this.info.total % this.info.size ) + 1;

the key total is still undefined, because the view is done before the service call is completed. key total 仍然未定义,因为视图是在服务调用完成之前完成的。

I tried to do the refresh function with promise, but the result is the same.我试图用promise来做刷新功能,但结果是一样的。 Is there a way I can wait to complete the variable before sending it to the child compoenent or that the child componet knows when the value was updated so it can execute the math?有没有办法在将变量发送给子组件之前等待完成变量,或者子组件知道值何时更新以便它可以执行数学运算?

As mentioned, a service would be the best way to go.如前所述,服务将是最好的方式。 You don't need to create a new Service, you can utilize the one you have and just make some additions.您不需要创建新的服务,您可以利用已有的服务并添加一些内容。 So add a Subject that the child component will subscribe to.所以添加一个子组件将订阅的Subject I have a simplified example set up for you:我为您设置了一个简化的示例:

The service, here I'm using your ListTableService服务,这里我使用你的ListTableService

private tableVar = new Subject<number>();

newTable = this.tableVar.asObservable();

tableReceived(table: string) {
  this.tableVar.next(table);
}

Parent component, when data has been retrieved父组件,当数据被检索时

 refresh(pageNumber : number, pageSize : number){
   this.mainService.get(pageNumber, pageSize).then(result => {
     this.table.total = result.data.total;
     this.listTableService.tableReceived(this.table); // add this!
   });
 }

And in your child, move the call of the updateFooter -function inside the subscription of table instead.而在您的孩子中,将updateFooter函数的调用移动到table的订阅中。 So in your child constructor:所以在你的子构造函数中:

constructor(public listTableService : ListTableService) {
   listTableService.newTable.subscribe(table => {
      this.info = table;
      this.updateFooter();
   })
}

Example plunker. 示例plunker。

One thing to notice, is that you MUST remove the provider of the service in the child component:需要注意的一件事是,您必须删除子组件中的服务提供者:

providers: [ListTableService]

Because if you do not, you will end up with a new instance of the service, that will not contain the table value set by the parent.因为如果你不这样做,你最终会得到一个新的服务实例,它不包含父级设置的table值。 When removing this provider, Angular will follow the hierarchy and find the next level provider, which would in your case be the parent with provider ListTableService , which means that your parent and child will share the same instance of the service.删除此提供程序时,Angular 将遵循层次结构并找到下一级提供程序,在您的情况下,该提供程序是具有提供程序ListTableService的父ListTableService ,这意味着您的父级和子级将共享相同的服务实例。

As a sidenote, I would though recommend that you do not declare providers in your components, if you do not explicitly want to have a new instance of a service.作为旁注,我建议您不要在组件中声明提供程序,如果您不明确希望拥有服务的新实例。 To declare your providers in the NgModule is much cleaner and easier to maintain :)NgModule声明你的提供者更干净,更容易维护:)

More about component interaction: shared service (+ other possibilities)有关组件交互的更多信息: 共享服务(+ 其他可能性)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM