离子和角度函数不返回值

时间:2019-04-27 02:26:05

标签: angular ionic-framework

我无法获得addReservation函数来返回任何值。

reservations.page.ts中,当我登录控制台时它将返回一个空数组。

userReservations: Reservation[];
private resSubscription: Subscription;
constructor(private resService: ReservationsService) { }

      ngOnInit() {
        this.resSubscription =
        this.resService.reservations.subscribe(reservations => {
          console.log('reservations...', reservations);
          this.userReservations = reservations;
        });
      }

下面是reservations.service.ts,我无法在return语句中获取保留值来记录任何值,因此我猜可能是问题所在。

export class ReservationsService {
  private _reservations = new BehaviorSubject<Reservation[]>([]);

  constructor(private authentication: AuthenticationService) { }

  // return the parking space reservations
  get reservations() {
    return this._reservations.asObservable();
  }

  // create a reservation
  addReservation(
    parkingSpaceId: string,
    parkingSpaceTitle: string,
    url: string,
    firstName: string,
    lastName: string,
    reservedDayCount: number,
    reservedFrom: Date,
    reservedTo: Date
  ) {
    const newReservation = new Reservation(
      Math.random().toString(),
      parkingSpaceId,
      this.authentication.userId,
      parkingSpaceTitle,
      url,
      firstName,
      lastName,
      reservedDayCount,
      reservedFrom,
      reservedTo
    );
    return this.reservations.pipe(
      take(1),
      tap(reservations => {
        console.log('return reservations...', reservations);
        this._reservations.next(reservations.concat(newReservation));
      })
    );
  }  
}

1 个答案:

答案 0 :(得分:3)

问题出在您的addReservation函数中。

以这种方式,只有在addReservation订阅后,抽头才会执行...这是错误的,因为这将导致无限循环。

以下链接显示如何专门使用Rxjs来管理Angular服务中的状态,而不必存储数据的任何本地副本

https://dev.to/avatsaev/simple-state-management-in-angular-with-only-services-and-rxjs-41p8

这是将模式应用于ReservationsService的方式:

export class ReservationsService {
   get reservations(): Reservation[] {
        return this._reservations.getValue();
   }

   private set reservations(val: Reservation[]) {
     this._reservations.next(val);
   }

   private _reservations = new BehaviorSubject<Reservation[]>([]);

   constructor(private authentication: AuthenticationService) { }

  // return the parking space reservations
  get reservations$() {
    return this._reservations.asObservable();
  }

  // create a reservation
  addReservation(
    parkingSpaceId: string,
    parkingSpaceTitle: string,
    url: string,
    firstName: string,
    lastName: string,
    reservedDayCount: number,
    reservedFrom: Date,
    reservedTo: Date
  ) {
    const newReservation = new Reservation(
      Math.random().toString(),
      parkingSpaceId,
      this.authentication.userId,
      parkingSpaceTitle,
      url,
      firstName,
      lastName,
      reservedDayCount,
      reservedFrom,
      reservedTo
    );
    this.reservations = [
      ...this.reservations, 
      newReservation
    ];

  }  
}