Uffo Uffo - 2 years ago 112
Javascript Question

Angular 2 undefined var on eval

So I have the following code:

@ViewChild('MondayPicker') MondayPicker;
@ViewChild('TuesdayPicker') TuesdayPicker;
@ViewChild('WednesdayPicker') WednesdayPicker;
@ViewChild('ThursdayPicker') ThursdayPicker;
@ViewChild('FridayPicker') FridayPicker;
@ViewChild('SaturdayPicker') SaturdayPicker;
@ViewChild('SundayPicker') SundayPicker;

working_days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
simpleColumns;
reservation_times;
currentUser;
private ngUnsubscribe: Subject<any> = new Subject<any>()

ionViewDidEnter(){

for(var i = 0; i < this.working_days.length; i++){
this.firebase.database.list('/schedule',{query: {orderByChild: 'user_day',equalTo: this.currentUser.uid+'_'+this.working_days[i] }})
.take(1)
.subscribe(
(data) => {
console.log(eval('this.'+data[0].day+'Picker.setValue("From 00: 00 TO 00: 00");'));
});
}
}


Now this line:


console.log(eval('this.'+data[0].day+'Picker.setValue("From 00: 00 TO
00: 00");'));


So what I'm trying to do will produce this:
this.MondayPicker.setValue("From 00: 00 TO
00: 00");


But I get
undefined
on
this.MondayPicker
for example, but If I do manually
this.MondayPicker.setValue("From 00: 00 TO
00: 00");
it works, why is this happening?

Answer Source

I think you should avoid using eval. Try this instead:

this[data[0].day + 'Picker'].setValue(...)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download