0

最近遇到了一些问题,想知道为什么我无法访问在 ngOnInit 函数中设置以供以后使用的对象,就像在另一个函数中一样?

我想this.appointmentDetailId在我的cancelAppointment()函数中访问和使用,但它是undefined. 希望有人可以提供帮助。谢谢。

这是我的代码:

export class AppointmentDetailComponent implements OnInit {
  id: any;
  appointmentDetailId: any;
  appointmentDetail$: Observable<AppointmentDetails>;
  appointmentDetail: AppointmentDetails;
  pageTitle = 'Some Default Title Maybe';

  constructor(
    private route: ActivatedRoute,
    private title: Title,
    private apiService: APIService
  ) {
    this.appointmentDetailId = this.id;
    console.log(this.appointmentDetailId);
  }

  ngOnInit() {
    this.route.paramMap
      .pipe(
        tap((params: ParamMap) => {
          this.id = params.get('id');
          // Or this.id = +params.get('id'); to coerce to type number maybe
          this.pageTitle = 'Termin Details: ' + this.id;
          this.title.setTitle(this.pageTitle);
        }),
        switchMap(() => this.apiService.getAppointmentDetailsById(this.id))
      )
      .subscribe((data: AppointmentDetails) => {
        this.appointmentDetail = data;
        console.log(this.appointmentDetail);
      });
  }

  cancelAppointment() {
    console.log(this.appointmentDetailId);
    this.apiService.cancelUserAppointment(this.appointmentDetailId);
  }
}
4

1 回答 1

2

在您设置的构造函数中,将值设置为(可能)this.appointmentDetailId = this.id的初始值;this.idundefined

后来你设置this.id = params.get('id')了,但这不会改变this.appointmentDetailId,因为它们是两个不同的对象。


如果您想this.appointmentDetailId始终匹配this.id,则应使其成为简单的包装器,而不是其自己的对象。

export class AppointmentDetailComponent implements OnInit {
  id: any;
  get appointmentDetailId() {
    return this.id;
  }
  set appointmentDetailId(value: any) {
    this.id = value;
  }

  // Other code
}

使用自定义getset方法,您仍然可以this.appointmentDetailId像访问它自己的字段一样访问 - 但它实际上与this.id. 现在,对任一字段的任何更改都将始终保持同步。

// Always true
this.appointmentDetailId === this.id

this.appointmentDetailId = 123;
this.appointmentDetailId === 123; // True
this.id === 123; // True;

this.id = "Test";
this.appointmentDetailId === "Test"; // True
this.id === "Test"; // True

或者,如果您可以简单地省略 set 方法,那么您将能够访问相同的值,但您无法更改它。

// Always true
this.appointmentDetailId === this.id

this.appointmentDetailId = 123; // Error

this.id = "Test";
this.appointmentDetailId === "Test"; // True
this.id === "Test"; // True
于 2018-09-11T15:51:31.710 回答