Ng-select Error: InvalidPipeArgument: '[object Object],[object Object]' for pipe 'AsyncPipe'

Ng-select Error: InvalidPipeArgument: '[object Object],[object Object]' for pipe 'AsyncPipe'

我正在尝试将我的打字稿模型绑定到来自后端的数据以显示在 ng-select 下拉列表中。我的 HTML for ng-select 如下所示:

<ng-select [items]="allEmp$ | async" bindLabel="empName" autofocus bindValue="id"[(ngModel)]="empName"></ng-select>

打字稿:

  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);
      })
  }

日志: 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
​

错误错误:InvalidPipeArgument:'[object Object],[object Object]' for pipe 'AsyncPipe'

根据模板,allEmp$ 需要一个 Observable。

[items]="allEmp$ | async"

但是,在 ts 文件中,您将数组分配给不可观察的 allEmp$。

this.allEmp$ = mapped[0].value; // returns array type

要解决此问题,

  1. 要么删除|来自 HTML(或)

    的异步管道
    <ng-select [items]="allEmp$"
    
  2. 在ts中赋值数组的observable

    this.allEmp$ = from(mapped[0].value); // import { from } from 'rxjs';
    
  1. 异步管道将数据从 Observable 传输到它的值。 您的代码应该是:

    [items]="allEmp$ | async"

ts:

   ngOnInit(): void {
    this.allEmp$ = this.getAllEmp();
   }

   getAllEmp(){
    this.empLoading = true;
    this.employeeService.getAll().pipe(
      map((data) => {
          this.empLoading = false;
          this.results = data;
          const mapped = Object.keys(this.results).map(key => ({type: key, 
                         value: this.results[key]}));
          return mapped[0]?.value;
         }),
    );
}