我希望客户类中的汽车对象为空而不是未定义,因为我有选择器来选择汽车对象,并且我希望它返回空而不是未定义。
这是我的初始状态。
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>
我收到一个错误,提示城市未定义。如果状态为空,如何获取空对象
答案 0 :(得分:2)
您至少有三个选择:
你可以在你的类中初始化必要的字段:
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[] = []
}
您可以在工厂方法中使用必要的字段初始化客户:
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()
};
让你的选择器状态返回一个有效值:
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>