Search code examples
typescriptrestapiionic4angular8

Get API call typescript with Angular


I'm facing to a problem concerning the call to my API Data. When I initialize my function into ngOnit(). I cannot display any data.

user.service.ts

  getUser(id): Observable<User[]> {
    return this.http.get<User[]>('http://localhost:8000/api/users/' + id)
      .pipe(
        tap(_ => console.log(`User fetched: ${id}`)),
        catchError(this.handleError<User[]>(`Get user id=${id}`))
      );
  }

user.page.ts

import { Component, OnInit } from '@angular/core';
import { UsersService } from "../services/user.service";

@Component({
  selector: 'app-users',
  templateUrl: './users.page.html',
  styleUrls: ['./users.page.scss'],
})
export class UsersPage implements OnInit {

  constructor(private userService: UsersService) { }

  ngOnInit() {
    this.userService.getUserList()
  }
}

Solution

  • Your services returns an observable, you will need to subscribe to it in the ngOnInit function. Assign the result to a public variable and use that in your HTML to display data.

    public users: User[] = [];
    ngOnInit () {
       this.userService.getUserList().subscribe ( users => {
           this.users = users;
           console.log ( this.users);
       });
    }