无法在组件内部设置类的值

时间:2019-05-06 03:28:56

标签: angular typescript angular7

我想手动设置类的属性,但目前无法设置。

当我的页面加载时,在ngOnInit上设置任何类型的计划。然后,单击按钮,我需要一个方法,该方法应该手动设置称为类的属性的值。不幸的是,设置该值会返回错误

  

错误TypeError:无法设置未定义的属性'operatorId'

这就是我在代码中的处理方式

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

很遗憾,在设置票证operatorId值之前登录operatorId时,我可以在控制台中看到一个值。但是在设置后它变得不确定。为什么会这样?手动设置类属性值的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

     // 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);
      }

当票证类具有很多属性时,使时间表和票证的类型与BookingPage类相同 那么您可以轻松地做到这一点

机票= this.schedule console.log(ticket.operatiorId)//您将得到答案

推荐:用于键入=>使用界面代替类。(即票证:票证)