如何从节点 API 获取数组形式的数据以在 Angular *ngFor 中使用

how to get data in array form from node API to use in Angular *ngFor

当我在 Angular *ngFor.

中使用从节点 API(mongoDB 集合)接收的数据时出现错误

错误指出数据应该是数组形式才能在 *ngFor 中使用。 在API的console log语句中,可以看到数据是数组形式 但是在 component.ts 的控制台日志语句中 - devtools 将其显示为一个对象。

如何获取纯数组形式的数据?

API 控制器:

exports.getNonuserEmployees = (req, res, next) => {
  let docQuery;

  docQuery = employee.find({ userName: { $eq: '' }});

  docQuery.sort('fName')
    .select('_id fName lName coEmail')
    .then( documents => {
        console.log(documents);
        res.status(200).json({
            nonuserEmployees: documents
        })
    })
    .catch(err => {
        res.status(500).json({
            message: "Server Error in fetching Clients data!"
        });
    });
}

Angular服务到达上面api控制器方法:

getNonUserEmployees(){
    return this.httpClient.get<any>(this.reqUrl+'/nonuser');
}

Component.ts :

export class AdminAccountsComponent implements OnInit {
    form: FormGroup;

    nonuserEmployees = [{
        employeeId: '',
        fName: '',
        lName: '',
        email: ''
    }];

    ngOnInit() {
        // ..code
    }

    this.employeesService.getNonUserEmployees()
        .subscribe(emps => {
            this.nonuserEmployees = emps;
            console.log(emps);
        }
    );
}

Component.html :

<mat-form-field class="w-12rem">
    <mat-label>Select Employee</mat-label>
    <mat-select matInput formControlName="employeeName">
        <mat-option *ngFor="let e of nonuserEmployees" [value]="e.fName">
            {{ e.fName }}
        </mat-option>
    </mat-select>
</mat-form-field>

结果:

解决方案 1:更改 API

的结果
exports.getNonuserEmployees = (req, res, next) => {
  let docQuery;

  docQuery = employee.find({ userName: { $eq: '' }});

  docQuery.sort('fName')
    .select('_id fName lName coEmail')
    .then( documents => {
        console.log(documents);
        res.status(200).json(documents)
    })
    .catch(err => {
        res.status(500).json(err);
    });
}

解决方案 2:在 front-end

上格式化结果
this.employeesService.getNonUserEmployees().subscribe(
  emps => {
    this.nonuserEmployees = Object.values(emps).flat();
    console.log(emps);
  }
);

例子:

var emps = {
  nonuserEmployees: [
    {
      coEmail: "email_1@gmail.com",
      fName: "fName_1",
      lName: "lName_1",
      _id: "A1"
    },
    {
      coEmail: "email_2@gmail.com",
      fName: "fName_2",
      lName: "lName_2",
      _id: "B2"
    }
  ]
};

console.log(Object.values(emps).flat());