【问题标题】:display fetched data from API does not work - Angular 8显示从 API 获取的数据不起作用 - Angular 8
【发布时间】:2020-07-16 16:18:01
【问题描述】:

我是 Angular 的新手,但我仍然不太了解它是如何工作的。 我从我构建的 API 中获取数据。它有效,因为我在邮递员中对其进行了测试。 我无法在我的 Angular 应用程序中显示它们,我不明白为什么。

我的api.service.ts

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

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

  private SERVER_URL  = 'http://localhost:8080/returnShelf';

  constructor(private httpClient: HttpClient) { }

  public get() {
    return this.httpClient.get(this.SERVER_URL);
  }


}

我的home.component.ts

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

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  books = [];
  constructor(private apiService: ApiService) { }

  ngOnInit() {
        this.apiService.get().subscribe((data: any[]) => {
            console.log(data);
            this.books = data;
        });
  }

}

我的home.component.html

<div style="padding: 13px;">

  <div *ngFor="let book of books">
    <h2>{{book.title}}</h2>

      <p>
        {{book.author}}
      </p>

  </div>
</div>

谁能解释为什么我仍然无法显示我的图书数据?

【问题讨论】:

  • 您在浏览器开发者工具中看到了什么?在网络选项卡上发出请求了吗? console.log 在控制台打印一些东西?
  • 可能是 cors 问题。看看浏览器的调试工具
  • 控制台:“跨域请求被阻止:同源策略不允许读取localhost:8080/returnShelf的远程资源。(原因:CORS请求未成功)”
  • 我不知道该怎么做
  • 你能试试这个 public get() { return this.httpClient.jsonp(this.SERVER_URL); } ...... insted of public get() { return this.httpClient.get(this.SERVER_URL); }

标签: angular typescript components angular8 ngfor


【解决方案1】:

你可以试试这个吗? 在 src 文件夹中创建 proxy.conf.json 文件并添加以下内容:

{
    "/api/*": {
        "target": "http://localhost:8080",
        "secure": false,
        "logLevel": "debug"
    }
}

接下来,打开angular.json文件,在指向src/proxy.conf.json文件的serve->options下添加proxyConfig键,如下:

"architect": {
  "serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "src/proxy.conf.json"
    },
  ...
  }
}

【讨论】:

    【解决方案2】:

    好的,我浏览了互联网,问题是我的后端没有映射 CORS。

    解决方案包括在 ApiApplication.java 中添加一个 corsConfigurer,这样:

     @Bean
            public WebMvcConfigurer corsConfigurer() {
                return new WebMvcConfigurer() {
                    @Override
                    public void addCorsMappings(CorsRegistry registry) {
                        registry.addMapping("/**").allowedOrigins("http://localhost:4200");
                    }
                };
            }
    

    感谢大家的支持!

    【讨论】:

      猜你喜欢
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 2020-04-03
      • 2015-08-22
      • 2019-01-08
      • 1970-01-01
      相关资源
      最近更新 更多