Home > Net >  How to GET data through HTTP GET requests from Angular to a locally running Spring Boot rest API on
How to GET data through HTTP GET requests from Angular to a locally running Spring Boot rest API on

Time:06-09

I did use the angular HttpClient. It could GET data from various APIs available online, but can't GET data from my spring boot RESTful API running from HTTP://localhost:8080/users

Could anyone tell what maybe the issue, and suggest some possible fixes?

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.scss'],
})
export class SignupComponent implements OnInit {
  data: Object;
  http: HttpClient;
  constructor(http: HttpClient) {
    this.http = http;
  }

  postdetail(): void {
    this.http
      .get('http://localhost:8080/users')
      .subscribe((data) => {
        this.data = data;
      });
  }

  ngOnInit(): void {}
}

CodePudding user response:

import { Component, OnInit } from '@angular/core';
import { ApiService} from 'path to api service';

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.scss'],
})
export class SignupComponent implements OnInit {
  data: MyDetailInterface;
  constructor(private apiService: ApiService) {}


  ngOnInit(): void {
   this.apiService.postDetail().subscribe((data) => {
    this.data = data;
  });
  }

}

Create a service api.service.ts instead of making the http call directly from your component:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

export const BASE_URI: string = "http://localhost:8080/"


@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private httpClient: HttpClient) { }

  postDetail(): Observable<MyDetailInterface> {
    return this.httpClient.get<MyDetailInterface>(BASE_URI   "users");
  }

}

Create the MyDetailInterface interface:

export interface MyDetailInterface {
    id: number;
    ....

   
  }
  • Related