2017-04-22 64 views
0

我在一個組件中有一個數組,它在Init過程中被初始化。基於@input值,數組需要修改。在onChanges期間,數組似乎是空的。這怎麼能實現?基於@Input的修改變量

export class SomeComponent implements OnInit, OnChanges { 
@Input() 
pickedStudents: Student[] = []; 
studentSubscription: Subscription; 
students: Student[] = []; 
constructor(private studentService: StudentService) { 
} 
ngOnInit() { 
    this.studentSubscription = this.studentService.getStudents().subscribe(a => this.students = a); 
} 
ngOnChanges() { 
    if (this.pickedStudents && this.pickedStudents.length) { 
     //This is for instance. The problem is students seem to be empty here. 
     this.students.splice(this.students.indexOf(this.pickedStudents[0]), 1); 
    } 
} 
ngOnDestroy() { 
    this.studentSubscription.unsubscribe(); 
} 
} 
+3

沒有人知道如果妳不顯示你的代碼發生什麼... –

+0

這是一個子組件或者這是否'pickedStudents'來從? – Alex

回答

0

只要把條件在ngOnChanges如下

ngOnChanges(){ 
    if(this.arrayName && this.arrayName.length){ 
      your operation 
    } 
}