简体   繁体   English

如何通过来自 Angular 的 HTTP GET 请求获取数据到端口 8080 上本地运行的 Spring Boot REST API?

[英]How to GET data through HTTP GET requests from Angular to a locally running Spring Boot rest API on port 8080?

I did use the angular HttpClient.我确实使用了有角度的 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它可以从在线可用的各种 API 获取数据,但无法从我的 Spring Boot RESTful API 获取数据,该 API 运行于 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 {}
}
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:创建一个服务api.service.ts而不是直接从您的组件进行 http 调用:

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:创建 MyDetailInterface 接口:

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

   
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM