I am getting error when I use the data received from node API (mongoDB collection) in Angular *ngFor.
The error states that the data should be in array form to be used in *ngFor. In console log statement of API, I can see that the data is in the array form But in the console log statement in component.ts - the devtools show it as an object.
How do I get the data in pure array form?
API controller :
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 service which reaches the above api controller method :
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>
Result :
Solution 1 : Change the result of the 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);
});
}
Solution 2 : Format the result on the front-end
this.employeesService.getNonUserEmployees().subscribe(
emps => {
this.nonuserEmployees = Object.values(emps).flat();
console.log(emps);
}
);
Exemple :
var emps = {
nonuserEmployees: [
{
coEmail: "[email protected]",
fName: "fName_1",
lName: "lName_1",
_id: "A1"
},
{
coEmail: "[email protected]",
fName: "fName_2",
lName: "lName_2",
_id: "B2"
}
]
};
console.log(Object.values(emps).flat());