I'm working on a small MEAN application. I've stored some user details on mongodb. I just want to fetch them and store them in a local array (actually the email id only). Fetching part I've done and it is working perfectly but I'm not able to save it correctly. Here's my code.
api.js
router.get('/allregisteredusers', function(req, res) {
User.find({}).exec(function(err, user) {
if (err) {
console.log("Error retrieving users");
}
else {
res.json(user);
console.log("Users: " + user); // OUTPUT IS CORRECT
}
});
});
The data is this:
Here's my service user.service.ts:
import { Injectable } from '@angular/core';
...
@Injectable({
providedIn: 'root'
})
export class UserService {
private _usersUrl = "http://localhost:3000/api/allregisteredusers";
constructor(private http: HttpClient) {
}
ngOnInit() {
this.getUsers();
}
getUsers() {
console.log("getUsers called");
return this.http.get<any>(this._usersUrl)
}
}
Up till here everything is working perfectly. The problem starts now: userlist.component.ts
import { Component, OnInit } from '@angular/core';
...
import { UserService } from '../user.service';
@Component({
...
})
export class UserListComponent implements OnInit {
registerUserType ={
firstName: "",
lastName: "",
email: "",
password: "",
userid: ""
};
users: []; // In this array I want to store Email ids of all users
constructor(..., private _userService: UserService) {
}
ngOnInit() {
this._userService.getUsers()
.subscribe(
res => {
console.log("Res: "+res); // Output: Res: [object Object],[object Object]
this.users = res.email
},
err => console.log(err)
)
console.log("List of all users: "+this.users); Output:// List of all users: undefined
}
}
I gently remind hereby that api code is correct as I've checked on Postman also. Please correct my mistake. Why I'm not able to store it. I just want the Email of the user not the entire thing. Please help.