在 Angular 中无法通过服务传递数据

问题描述 投票:0回答:0

我是 Angular 的新手,在使用服务传递数据时遇到问题。我有两个名为 Input 和 Appointments 的组件。我将我的“appointmentList”数组存储在这样的数据源文件中:

export const appointmentList:Appointment[] = [
    
]

在我的输入组件中创建一个像这样的新对象

var newAppointment = new Appointment(this.id, this.userName, this.dayName, this.intervalVal, this.procecess, this.totalPrice)
        appointmentList.push(newAppointment)

我创建了一个服务,它返回一个名为 getAppointmentList 的 Observable 方法,如下所示:

 getAppointmentList(): Observable<Appointment[]> {
    return of(appointmentList);
  }

并且在我的 AppointmentComponent 中尝试将 appointmentList 提取到另一个数组,如下所示

export class AppointmentComponent implements OnInit {

  appointList : Appointment[] | undefined

  constructor(private appointmentService: AppointmentService) {}

  ngOnInit(): void {
    this.appointmentService.getAppointmentList().subscribe(appoint => {
      this.appointList = appoint
    })
  }
  
}

我可以确认在 InputComponent 中,我的代码将 newAppoitnment 推送到 appointmentList,但是每当我路由到 Appointment 组件时,我的 appointmentList 就会重置。

谢谢大家的帮助!

我试过像这样在我的服务类中分配 productList:

appointmentList : Appointment[] | undefined

但这没有用。我期待我的 appointmentList 可以使用来自 Input 组件的新约会对象进行更新,并希望使用 *ngfor 模块来呈现它们。

arrays angular routes service subscribe
© www.soinside.com 2019 - 2024. All rights reserved.