gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:45:05 26 4
gpt4 key购买 nike

我希望客户类中的汽车对象为空而不是未定义,因为我有选择器来选择汽车对象,我希望它返回空而不是未定义。

这是我的初始状态。

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

这是我的带选择器的 reducer 。

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>

关于angular - 将初始状态对象初始化为空对象而不是未定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66145715/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com