Rishikesh-12
Rishikesh-12

Reputation: 63

HTTP Get Request in Angular

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)

Upvotes: 0

Views: 1132

Answers (2)

Rebai Ahmed
Rebai Ahmed

Reputation: 1600

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)
  }

}

Upvotes: 1

usalin
usalin

Reputation: 141

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

Upvotes: 0

Related Questions