0

I'm trying to invoke my REST API to get some data and display them in html page Using Angular 10. here's my my http service.

public findUsers(page: number, size: number): Observable<User[]> {
  return this.http.get<User[]>(AUTH_API+`users?page=${page}&size=${size}`, httpOptions);
}

And here's my service's call.

  export class AccountComponent implements OnInit {
  paginator: MatPaginator = {} as MatPaginator;
  loaded: boolean;
  users: User[];
  data:any;

  constructor(private accountSerive: AccountService) { }

  ngOnInit(): void {
    this.paginator.pageIndex = 0;
        this.paginator.pageSize = 20;
    this.getUsers();
  }
  getUsers() {
    this.data = this.accountSerive.findUsers(this.paginator.pageIndex, this.paginator.pageSize)
    .subscribe((data) => {
      this.users = data;
      this.loaded = true; 
    });
  }

}

Here's my HTML code

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

And finally my user Model

    export interface User {
    email: string;
    password: string;
    userName: string;
    roles: [Role]; 

}
export interface Role {
    name: string; 
    
}

Here the data content enter image description here

4
  • 1
    It appears this.users isn't an array. Do a console.log(data) inside the subscription and post the screenshot. Commented Nov 15, 2020 at 18:17
  • 1
    Or you don't have differences for all arrays. Just add some identifiable keywords to each objects. Commented Nov 15, 2020 at 18:23
  • console.log(data) => {content: Array(5), totalElements: 5} content: (5) [{…}, {…}, {…}, {…}, {…}] Commented Nov 15, 2020 at 19:10
  • dev.to/jwp/angular-why-doesn-t-my-data-show-up-4efm Commented Nov 16, 2020 at 0:47

1 Answer 1

1

The data you receive from the API apparently is returned in this format:

{
  content: User[],
  totalElements: number
}

So the actual array of results can be found under a property called content. So you need to map your call to this property like this:

// return type
export interface UsersDto {
  content: User[];
  totalElements: number;
}

public findUsers(page: number, size: number): Observable<User[]> {
    return this.http.get<UsersDto>(AUTH_API+`users?page=${page}&size=${size}`, httpOptions)
             .pipe(map(result => result.content));
}
Sign up to request clarification or add additional context in comments.

2 Comments

content is not declared any where !
I updated the code to reflect the correct return value from the endpoint

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.