user14846818
user14846818

Reputation: 29

How to fix get users in posts?

I'm write project for learning Angular. My project displays posts. I want to output users in table. I have to use method in my template (for example getUser(id)). But it works strange (Usernames are displayed as "Bret,,,,,,,,, ,Antonette,,,,,,,, ,,Samantha,,,,,,," ect). How to fix this problem?

All project posts project

posts.component.ts:

getUsername(id: any) {
    return this.users.map((us: any) => {
      return us.id == id ? us.username : "";
    });
  }

posts.component.html:

<table>
  <colgroup>
    <col style="width: 10%;" />
    <col style="width: 15%;" />
    <col style="width: 75%;" />
  </colgroup>
  <thead>
    <tr>
      <th *ngFor="let column of columns">{{ column.title }}</th>
    </tr>
    <tr [formGroup]="form">
      <th *ngFor="let column of columns">
        <ng-container *ngIf="column.filterKey">
          <input type="text" [formControlName]="column.filterKey" />
        </ng-container>
      </th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let item of posts">
            <td>{{ item.userId }}</td>
            <td>
                {{ getUsername(item.userId) }}
            </td>
            <td>
                <a [routerLink]="['/posts', item.id]">{{ item.title | titlecase }}</a>
            </td>
        </tr>
  </tbody>
</table>

Upvotes: 0

Views: 50

Answers (2)

CyberEternal
CyberEternal

Reputation: 2545

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. For the not-matched users, it's inserting an empty string.

If It possible to request a user by unknown id, for which matched user can not be found, use this example

getUsername(id: any) {
    return this.users
        .find((us: any) => us.id === id)?.username || '';
     
}

Otherwise

getUsername(id: any) {
    return this.users
        .find((us: any) => us.id === id)
        .username;
}

Upvotes: 0

Jeremy Thille
Jeremy Thille

Reputation: 26390

Thats because your getUsername function returns ["Bret","","","","Antonette", "", ""]. You need to find only the user you're looking for, and return their name :

getUsername(id: any) {
    return this.users
        .find((us: any) => us.id == id)
        .username;
}

Upvotes: 2

Related Questions