Patrick
Patrick

Reputation: 69

Load users from backend using angular / express

Im doing a little project with the MEAN stack and seem to be a little lost with something here. I can load a single user from MongoDB just fine, but I seem to be a little lost with loading all.

In my routes file I have

router.get('/admin, function(req, res, next) {
  User.find(function (err, user) {
    if(err) return next(err);
  }
});

I get the results from the database such as:

{"role":"user","_id":"5ade3f1c303744098c0acef1","firstname":"testFName","surname":"testSName","username":"testusername","password":"$2a$10$db1yx10Y3XOyyMt25PA5bOK3qso9fTxf9iOOWMapT7/Vt5n2gfCFC","email":"[email protected]","phonenumber":"0851234567","housename":"Villa Maria","addressline1":"Listry","addressline2":"Killarney","addressline3":"","county":"Kerry","__v":0}

Im following a guide, but it doesn't seem to cover this next part, I was wondering if anyone knew what I should do. I do know that I want to use *ngFor in a table somewhere.

I have called my authService and my router in my constructor

user: Object;

ngOnInit(){
  this.loadUsers();
}

public loadUsers() {
  this.authService.getUsers().subscribe((data) => {
    this.user = data;
}

in my table I was using

<tr *ngFor="let user of users">
  <td>{{ user.username }} </td>

But I keep getting a not defined error. I can't seem to see how it is not defined.

Upvotes: 0

Views: 76

Answers (1)

Alexander Leonov
Alexander Leonov

Reputation: 4794

It is pretty standard mistake. Angular gives you this error because it tries to render *ngFor immediately upon component creation while calling service takes time and it brings result later. You should add something like *ngIf="users != null" to your template and put *ngFor inside it. Always check the array you're going to render with *ngFor to avoid this error, or make sure in the code that your array property never gets null or undefined value.

Upvotes: 1

Related Questions