I want to set the properties of a class manually but I am unable to do so at the moment.

When my page loads, schedule of type any is set at ngOnInit. Then at the click of a button, I want a method which should manually set the value of a property of a class called. Unfortunately setting the value is returning the error

ERROR TypeError: Cannot set property 'operatorId' of undefined

Here is what how I am going about it in my code

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { ScheduleService } from './../schedules/schedule.service';
import { Ticket } from './../ticket/ticket';

@Component({
  selector: 'app-booking',
  templateUrl: './booking.page.html',
  styleUrls: ['./booking.page.scss']
})
export class BookingPage implements OnInit {
  schedule: any;
  ticket: Ticket;

  constructor() { }

  ngOnInit() {
    // set the schedule ID
    this.route.queryParams.subscribe(params => {
      this.scheduleId = params['schedule'];
    });

    this.selectedSchedule(this.scheduleId);
  }

  // get schedule selected
  selectedSchedule(scheduleId: string) {
    this.scheduleService.getSchedule(scheduleId).then(data => {
      this.schedule = data;
    });
  }

  // buy ticket
  buyTicket(ticket: Ticket) {
    console.log(this.schedule.operatorId); // operator ID is logged
    ticket.operatorId = this.schedule.operatorId;
    console.log(ticket.operatorId); // ERROR TypeError: Cannot set property 'operatorId' of undefined
  }
}

Strangly, I am able to see a value in the console when I log the operatorId before setting the ticket operatorId value. But it becomes undefined after setting it. Why is this the case and what is the best way to set a class property value manually?

1 Answers

0
Community On
     // buy ticket
      buyTicket(ticket: Ticket) {
        console.log(ticket) // first identify it is defined or not ? if it is undefined then intialize it like below based on the type of operatorId 
        ticket = {operatorId : ''} // considered operatorId as string
        console.log(this.schedule.operatorId); // operator ID is logged
        ticket.operatorId = this.schedule.operatorId;
        console.log(ticket.operatorId);
      }

When Ticket class has a lot of properties make the types of schedule and ticket as same in BookingPage class then you can easily do like this

ticket = this.schedule console.log(ticket.operatiorId) // you will get the answer

Recommendation: for typing => Use interface instead of class.(i.e ticket : Ticket)