初始化初始状态对象为空对象,而不是undefined



我希望customer类中的cars对象为空而不是未定义,因为我有选择器来选择cars对象,并且我希望它返回空而不是未定义。

这是我的初始状态。

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[]
}

这是我的减速器与选择器。

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

让你的选择器状态返回一个有效值:

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>

最新更新