如何解决Typescript 严格模式无法将 Observable 异步分配给 primeNg 下拉组件
我正在使用 p-dropdown primeNg 组件,从我所见,这应该能够采用 Observable |异步值并正确使用它,但 Typescript 严格模式不允许这样做,给
错误 TS2322:输入“客户[]”| null 不可分配给类型 'any[]'"
customers.html
<p-dropdown
[options]="customers$ | async"
placeholder="Select a customer:"
optionLabel="name"
[showClear]=true"
formControlName=selectedCustomer"
</p-dropdown>
customers.component.ts
customers$!: Observable<Customer[]>;
ciForm!: FormGroup;
constructor(private: fb: FormBuilder,private customerEntityService: CustomerEntityService){}
ngOnInit() {
this.ciForm = this.fb.group({
selectedCustomer: [null],selectedReason: [null],selectedId: [null],comments: ['']
});
this.ciCustomers$ = this.customerEntityService.entities$
.pipe(
map(customer => customer)
);
}
customer.model.ts
export class Customer {
public name: string = '';
public phoneNumber: string = '';
}
我的印象是使用“!”在变量之后表示它肯定会有一个值,这是因为数据是在加载组件之前在路由解析中获取的,但这对编译器来说似乎无关紧要。有关如何解决此问题的任何帮助?我对此无能为力。 primeNg 社区论坛似乎也没有帮助解决这个问题。
我知道我可能可以声明另一个变量并订阅 entityCache 中的数据,然后将该数据传递给选项,但异步管道的重点是我不应该这样做。
解决方法
异步管道返回数据类型或空值。您需要做的是使用 *ngIf="customers$ | async as customers" [options]="customers"
。
你也可以在你的代码周围使用一个容器并在那里添加结构化指令。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。