0

I have this url=https://reqres.in/api/users?page=2 and I am using a get request to fetch the data.

user.ts is an interface

export interface User {
    id:number,
    email:string,
    first_name:string,
    last_name:string,
    avatar:string
}

user.service.ts is a service

getAllUsers() :  Observable<User[]> {
  return this.http.get<User[]>("https://reqres.in/api/users?page=2");    
}

user.component.ts

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

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {

  constructor(private userService: UserService) { }

  public user =[];

  ngOnInit(): void {
    this.userService.getAllUsers().subscribe(data => this.user = data)
  }

}

I want to get the data object from the response object of 'GET' request and make a array of users.

Error: src/app/user/user.component.ts:16:54 - error TS2322: Type 'User[]' is not assignable to type 'never[]'.

16     this.userService.getAllUsers().subscribe(data => this.user = data)
                                                        ~~~~~~~~~


Error: src/app/user/user.component.ts:16:54 - error TS2322: Type 'User[]' is not assignable to type 'never[]'.
  Type 'User' is not assignable to type 'never'.

16     this.userService.getAllUsers().subscribe(data => this.user = data)
4
  • you need to subscribe to the get request. then you can access the data. get(...).subscribe(response => console.log(response)) Commented May 23, 2021 at 20:51
  • I believe it is data.data that you want. Commented May 23, 2021 at 21:21
  • public user: User[] = [] should do the trick Commented May 23, 2021 at 21:26
  • Why are you assigning a value to user before ngOnInit anyways? Commented May 23, 2021 at 21:28

2 Answers 2

1

What about changing the user type in your component:

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

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {

  constructor(private userService: UserService) { }

  public users: User [] =[];

  ngOnInit(): void {
    this.userService
      .getAllUsers()
     .subscribe(data => this.user = data)
  }

}
Sign up to request clarification or add additional context in comments.

Comments

0

You actually needed to create an interim object to access the Users[] - that is why you were having that type error. You can fix that by using pipe and passing data you want inside the object back to the component.

Let me know if you need further help.

Stackblitz

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.