Search code examples
angulartypescriptprimengngrx-entityprimeng-dropdowns

Typescript strict mode cannot assign Observable async to primeNg dropdown component


I am using the p-dropdown primeNg component and from what I can see this should be able to take an Observable | async value and use it properly but the Typescript strict mode will not allow this, giving

error TS2322: Type 'Customers[] | null is not assignable to type '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 = '';
}

I was under the impression that using the "!" after the variable denoted that it definitely will have a value, which is the case since the data is being fetched in the route resolve prior to loading the component, but this doesn't seem to matter to the compiler. Any help as to how to fix this? I am at my wits end on this. The primeNg community forums seem to be of no assistance in getting this resolved either.

I know I probably can declare another variable and subscribe to the data in the entityCache and then pass that data to the options but the whole point of the async pipe is that I shouldn't HAVE to do that.

Does anyone have a suggestion as to what I need to do to fix the null issue?


Solution

  • The async pipe returns data type or null. What you need to do is to use *ngIf="customers$ | async as customers" [options]="customers".

    You could also use a container around you code and add the structured directive there.