我正在开发一个小项目,我正在尝试让我的后端和前端通过 HTTP 请求通信数据。我回到了 Spring 应用程序,仅在端点“http://localhost:8080/api/grid/generate?size=4”处发布彩色网格的数据(目前已硬编码)。
我检查了一下,该帖子正在自行解决,并发布在应该的地方:
{
"grid": [
[
{
"color": "#9a8ca3",
"gridPosition": [0, 0]
},
{
"color": "#6382f1",
"gridPosition": [0, 1]
},
{
"color": "#9f4f77",
"gridPosition": [0, 2]
},
{
"color": "#6382f1",
"gridPosition": [0, 3]
}
],
[
{
"color": "#0632ea",
"gridPosition": [1, 0]
},
{
"color": "#9a8ca3",
"gridPosition": [1, 1]
},
{
"color": "#9f4f77",
"gridPosition": [1, 2]
},
{
"color": "#5e6c0f",
"gridPosition": [1, 3]
}
],
[
{
"color": "#9a8ca3",
"gridPosition": [2, 0]
},
{
"color": "#5e6c0f",
"gridPosition": [2, 1]
},
{
"color": "#FFFFFF",
"gridPosition": [2, 2]
},
{
"color": "#0632ea",
"gridPosition": [2, 3]
}
],
[
{
"color": "#74e57b",
"gridPosition": [3, 0]
},
{
"color": "#0632ea",
"gridPosition": [3, 1]
},
{
"color": "#74e57b",
"gridPosition": [3, 2]
},
{
"color": "#74e57b",
"gridPosition": [3, 3]
}
]
],
"emptyCellPosition": [2, 2]
}
现在来说“棘手”的部分:在角度上,为了获得我的网格,我在相应的服务中写了这个:
import { Injectable } from '@angular/core';
import { CellComponent } from '../components/cell/cell.component';
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs";
@Injectable({
providedIn: 'root'
})
export class GridService {
private readonly apiUrl = 'http://localhost:8080/api/grid';
private constructor(private readonly http: HttpClient) {}
// Generate grid from backend API
public generateGrid(size: number): Observable<{ grid: CellComponent[][], emptyCellPosition: [number, number] }> {
console.log("Url used: ",`${this.apiUrl}/generate?size=${size.toString()}` );
return this.http.get<{ grid: CellComponent[][], emptyCellPosition: [number, number] }>(`${this.apiUrl}/generate?size=${size.toString()}`);
}
这是我在网格组件中写的:
public constructor(private readonly gridService: GridService) {
}
public ngOnInit(): void {
this.initGrid();
}
private initGrid(): void {
this.gridService.generateGrid(this.size).subscribe({
next: ({ grid, emptyCellPosition }) => {
this.grid = grid;
this.emptyCellPosition = emptyCellPosition;
this.score = 0;
},
error: (err) => {
console.error('Error generating grid:', err);
}
});
}
我似乎在任何地方都找不到错误,并且分析渲染页面中的“网络”没有显示正在发出任何获取请求。我是瞎了还是在 Angular 中犯了菜鸟错误?
我检查了 URL,如果它不正确,我尝试对其进行硬编码,但它没有改变任何内容。我还使用 any 类型进行了检查,但也没有给出正确的结果。我还检查了 get 函数是否有效并返回了一个 observable,它确实做到了(“Observable2”)。
来自 API 调用的数据应该返回一个对象数组,但它返回的是一个数组数组(其中包含对象),如果您没有在 HTML 中考虑到这一点,则渲染可能不会发生。您可以使用数组方法
flat
来展平数组数组,以便您拥有单个数组。
public constructor(private readonly gridService: GridService) {
}
public ngOnInit(): void {
this.initGrid();
}
private initGrid(): void {
this.gridService.generateGrid(this.size).subscribe({
next: ({ grid, emptyCellPosition }) => {
this.grid = grid.flat(); // <- changed here!
this.emptyCellPosition = emptyCellPosition;
this.score = 0;
},
error: (err) => {
console.error('Error generating grid:', err);
}
});
}