如果这有帮助 - 我已经设置了:
请求流程:
-> SPA (Cookie) -> BFF (Token) -> API
SPA 是让我头疼的一个,因为我无法让它显示或解释获取的数据,尽管我基本上是在复制(工作)Microsoft 代码。
至于获取的数据 - 这是此处看到的
WeatherForecastController
的默认结果:
using ErpBridge.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ErpBridge.Server.WebApi.Controllers;
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
public WeatherForecastController()
{
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
SPA 使用 BFF 的代理(来自 GitHub 的 OidcProxy)向那里发送请求,
weather.component.ts
中的 Angular 组件如下所示:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-weather',
templateUrl: './weather.component.html',
styleUrl: './weather.component.scss'
})
export class WeatherComponent {
public forecasts: WeatherForecast[] = [];
constructor(http: HttpClient) {
http.get<WeatherForecast[]>('api/weatherforecast').subscribe(
{
next: (v) => this.forecasts = v,
error: (e) => console.error(e),
complete: () => console.info('complete')
});
}
}
interface WeatherForecast {
date: string;
temperatureC: number;
temperatureF: number;
summary: string;
}
weather.component.html
中的模板如下所示:
<p *ngIf="!forecasts?.length"><em>Loading...</em></p>
<table class='table table-striped' aria-labelledby="tableLabel" *ngIf="forecasts.length">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let forecast of forecasts">
<td>{{ forecast.date }}</td>
<td>{{ forecast.temperatureC }}</td>
<td>{{ forecast.temperatureF }}</td>
<td>{{ forecast.summary }}</td>
</tr>
</tbody>
</table>
我已验证对“api/weatherforecast”的请求是:
[
{
"date": "2024-03-02",
"temperatureC": 54,
"temperatureF": 129,
"summary": "Freezing"
},
{
"date": "2024-03-03",
"temperatureC": 5,
"temperatureF": 40,
"summary": "Freezing"
} // redacted for brevity
]
有人可以告诉我我做错了什么吗?我很确定我处理不当:
WeatherForecast
数组)提前致谢
我尝试了各种方法来处理 API 生成的 JSON 响应,基于:
我期望什么?老实说 - 某种错误消息为我指明了正确的方向。可悲的是我错过了任何...
说实话 - 我对 C# 非常熟悉 - 但我在 Angular 和 TS 方面都是新手。
在新的一天里,我重新审视了 Angular 文档。
我忘记将我的组件包含到 NgModule:declarations 中。
代码现在工作正常...