【问题标题】:Why am I unable to get access to object that was set on ngOnInit为什么我无法访问在 ngOnInit 上设置的对象
【发布时间】:2019-02-16 04:16:02
【问题描述】:

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

我想在我的cancelAppointment() 函数中访问和使用this.appointmentDetailId,但它是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);
  }
}

【问题讨论】:

    标签: javascript angular class constructor ngoninit


    【解决方案1】:

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

    稍后您设置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
    

    【讨论】:

    • 感谢您非常详细的解释!太好了,这行得通。干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    相关资源
    最近更新 更多