angular - 尽管有跨源支持(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 上的页面的图像
我可能哪里出错了?
提前致谢!
解决方案
在浏览器开发者工具中检查你的 api 的获取和发布请求,并确保 Angular 获取响应。如果从 api 获得任何成功的响应,则您的问题可能是对象映射问题,例如文件名。
推荐阅读
- css - 为什么单击锚链接会将 div 推到页面顶部?
- react-native - 反应本机应用程序不捆绑
- linux - 当我通过 Git Bash 中的 ssh 在远程 Linux 机器上运行命令时,如何将文件的内容直接复制到我的 Windows 剪贴板中?
- javascript - 将属性添加到字符串内的元素
- react-native - react-native-nested-scroll-view:processDebugManifest FAILED
- servicestack - 提供时自动查询参数如何工作
- reactjs - Reducer 状态没有被新对象更新 [redux, redux-toolkit, normalize]
- emacs - 如何从组织模式代码块中提取代码?
- data-structures - 在实践中哪个优先级队列更快?
- java - 有多少种方法我们可以在 6 个球/投球中至少得分 6 个?