首页 > 解决方案 > 尽管有跨源支持(Angular + Spring),但数据未在 Angular 中显示

问题描述

我正在尝试使用 Spring 和 Angular 构建一个完整的堆栈应用程序。

我已经成功配置了我的 REST API,它们在端口 8080 上运行良好。但是,当我尝试通过前端(Angular 服务)访问它们时,页面加载完美,但没有显示任何数据。我在 Spring 的界面中添加了跨源支持,因此控制台窗口中也不会显示任何错误。

但是,它表明检索到的数据是未定义的。(附图片)

客户列表组件(打字稿)

import { Component, OnInit } from '@angular/core';
import { Customer } from 'src/app/common/customer';
import { CustomerService } from 'src/app/services/customer.service';

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

  customers: Customer[];

  constructor(private customerService: CustomerService) { }

  ngOnInit() {

    this.listCustomers();
  }

  listCustomers() {
    this.customerService.getCustomerList().subscribe(
      data => {
        this.customers = data;
        console.log(`Data retrieved: ${this.customers}`);
      }
    );
  }
}

客户组件 (html)

<p>
    this works!
</p>

<p *ngFor = "let tempCust of customers">
    hello
    {{ tempCust.name }}
</p>

客户服务

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Customer } from '../common/customer';
import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';


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

  private baseUrl = 'http://localhost:8080/api/customerDetails';

  constructor(private httpClient: HttpClient) { }

  getCustomerList(): Observable<Customer[]> {
    return this.httpClient.get<GetResponse>(this.baseUrl).pipe(
      map(response => response._embedded.customers)
    )
  }
}

interface GetResponse{
  _embedded : {
    customers: Customer[];
  }
}

端口 4200 显示在端口 4200 上的页面的图像

端口 8080 显示在端口 8080 上的页面的图像

我可能哪里出错了?

提前致谢!

标签: angularspringtypescript

解决方案


在浏览器开发者工具中检查你的 api 的获取和发布请求,并确保 Angular 获取响应。如果从 api 获得任何成功的响应,则您的问题可能是对象映射问题,例如文件名。


推荐阅读