Typescript strict mode cannot assign Observable async to primeNg dropdown component
Asked Answered
F

2

6

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?

Fossick answered 9/2, 2021 at 17:39 Comment(3)
Where are you setting/filling customers$..?Iconology
@Iconology in the resolve for the route, but that isn't relevant to why it won't build.Fossick
$any(name$ | async) worked for me.Drawknife
B
0

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.

Bizerte answered 9/2, 2021 at 18:46 Comment(1)
Thank you! I am not sure why I didn't think of this but it works without issues!Fossick
K
-1

test on -- angular 14 + primng 14 you can add the "!" typescript operator to prevent null checks and to prevent null you can add rxjs operator startWith([]) to your code

<p-dropdown [options]="(customers$ | async)!" </p-dropdown>
Korrie answered 19/10, 2022 at 14:26 Comment(2)
someomr gave me DEVOTE - but i repeat i check my answer and it is working goodKorrie
It should be like this: [options]="(customers$ | async)!"Scarce

© 2022 - 2024 — McMap. All rights reserved.