将初始状态对象初始化为空对象而不是未定义的

Initialize the initial state object to be an empty object instead of undefined

我希望客户 class 中的汽车对象为空而不是未定义,因为我有 select 或者 select 汽车对象,我希望它 return 空而不是未定义。

这是我的初始状态。

export const initialState: CustomerState = {
  customer: new Customer(),
};

export class Customer{
id: number;
age: number;
cars: carClass;
phoneNumbers: string[];
}

export class carClass{
name:string;
citiesRegistered:city[];
}

export class city{
parks: string[],
lakes: string[],
schools: string[]
}

这是我的减速器 selector.

const getCustomerState= createFeatureSelector<CustomerState>('customer');

export const getCustomerCarsCities = createSelector(
  getCustomerState,
  state => state.customer.cars.citiesRegistered   // There is an error here
);

这是注册城市的组件

  getCustomerCitiesRegistered$: Observable<any>;

  constructor(private store: Store) {
    this.getCustomerCitiesRegistered$ = this.store.select(getCustomerCarsCities );
  }

这是html

<div *ngIf="getCustomerCitiesRegistered$ | async as cities">   // This is undefined
   
    <div class="parks">
      <app-parks [parkOptions]="cities.parks">
      </parks>
    </div>
</div>

我收到城市未定义的错误。如果状态为空,我怎样才能得到一个空对象

您至少有三个选择:

选项 1:

您可以在 类:

中初始化必要的字段
export class Customer {
  id: number;
  age: number;
  cars = new CarClass(); // Since you access this it needs to be initialized.
  phoneNumbers: string[] = []; // It is good practice to use empty arrays over null | undefined.
}

export class CarClass {
  name:string;
  citiesRegistered: City[] = []; // Since you access this it needs to be initialized.
}

export class City {
  parks: string[] = [],
  lakes: string[] = [],
  schools: string[] = []
}

选项 2

您可以在工厂方法中使用必要的字段初始化客户:

const createEmptyCustomer = () => {
    const customer = new Customer();
    customer.cars = new CarClass();
    customer.cars.citiesRegistered = [];

    // maybe init more fields...

    return customer;
};

export const initialState: CustomerState = {
  customer: createEmptyCustomer()
};

选项 3

让您的选择器声明 return 一个有效值:

export const getCustomerCarsCities = createSelector(
  getCustomerState,
  state => state.customer?.cars?.citiesRegistered || []
);

如果您打算修改数组,则不建议使用最后一个选项,因为它不会反馈给客户。

现在你有第二个问题

您正在引用 cities.parks:

<div class="parks">
  <app-parks [parkOptions]="cities.parks"></app-parks>
</div>

这是行不通的,因为您实际上是在写 [].parks。 也许你打算写一个循环或其他东西:

<div class="parks">
  <ng-container *ngFor="let city of cities">
    <app-parks [parkOptions]="city.parks"></app-parks>
  </ng-container>
</div>