I am trying to bind my typescript model to data from the backend to display in an ng-select dropdown. My HTML for ng-select looks like the following:
<ng-select [items]="allEmp$ | async" bindLabel="empName" autofocus bindValue="id"[(ngModel)]="empName"></ng-select>
TypeScripts:
results;
empData;
empLoading = false;
allEmp$: Observable<any[]>;
ngOnInit(): void {
this.getAllEmp()
}
getAllEmp(){
this.empLoading = true;
this.employeeService.getAll()
.subscribe(
data => {
this.results = data ;
console.log(this.results); //1
this.empLoading = false;
const mapped = Object.keys(this.results).map(key => ({type: key, value: this.results[key]}));
console.log(mapped);
this.allEmp$ = mapped[0].value;
console.log(this.allEmp$);
}, error =>{
console.log(error);
})
}
Logs: 1
{
"results": [
{
"id": 1,
"empName": "Emp01"
},
{
"id": 2,
"empName": "Emp02"
}
]
}
2
[
{
"type": "results",
"value": [
{
"id": 1,
"empName": "Emp01",
},
{
"id": 2,
"empName": "Emp02"
}
]
}
]
3
Array [ {…}, {…} ]
0: Object { id: 1, empName: "Emp01", … }
1: Object { id: 2, empName: "Emp02", … }
length: 2
ERROR Error: InvalidPipeArgument: '[object Object],[object Object]' for pipe 'AsyncPipe'
As per the template, allEmp$ expects an Observable.
[items]="allEmp$ | async"
But, in ts file, you are assigning the array to allEmp$ which is not observable.
this.allEmp$ = mapped[0].value; // returns array type
To fix the issue,
Either remove | async pipe from HTML (or)
<ng-select [items]="allEmp$"
Assign observable of the array in ts.
this.allEmp$ = from(mapped[0].value); // import { from } from 'rxjs';