【问题标题】:Typescript strict mode cannot assign Observable async to primeNg dropdown componentTypescript 严格模式无法将 Observable 异步分配给 primeNg 下拉组件
【发布时间】:2021-02-09 17:39:22
【问题描述】:

我正在使用 p-dropdown primeNg 组件,据我所知,这应该能够采用 Observable | async 值并正确使用它,但 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 中的数据,然后将该数据传递给选项,但异步管道的重点是我不应该这样做。

有人对我需要做什么来解决 null 问题有建议吗?

【问题讨论】:

  • 你在哪里设置/填充客户$..?
  • @MikeOne 解决了路由问题,但这与它无法构建的原因无关。

标签: angular typescript primeng ngrx-entity primeng-dropdowns


【解决方案1】:

异步管道返回数据类型或 null。你需要做的是使用*ngIf="customers$ | async as customers" [options]="customers"

您还可以在代码周围使用容器并在其中添加结构化指令。

【讨论】:

  • 谢谢!我不知道为什么我没有想到这一点,但它没有问题!
猜你喜欢
  • 2015-05-23
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 2019-07-08
  • 2013-12-06
  • 1970-01-01
  • 2019-06-29
  • 2011-09-11
相关资源
最近更新 更多