【问题标题】:Problem with fetch data from api to client in angular以角度从api到客户端获取数据的问题
【发布时间】:2022-12-08 23:07:54
【问题描述】:

我在我的网络应用程序中使用 httpClient 将数据获取到客户端时遇到问题。 当我检查服务器时一切正常 Postman ,但角度返回空对象的客户端。 那是我的 ICalendar 界面:

export interface ICalendar {
  calendarName: string;
  userId: number;
  training: Array<{
    trainingTittle: string;
    date: string;
    excercises: Array<{
      excerciseName: string,
      numOfRepeat: number
   }>
  }>;
}

这就是我获取服务数据的方式:

 export class CalendarService {
  constructor(private http: HttpClient) { }

  public getAllTrainings() {
    return this.http.get<ICalendar[]>('https://localhost:5001/api/calendar');
  }

这就是调用方法的样子:

  ngOnInit(): void {
this.calendarService.getAllTrainings()
  .subscribe(data => {
    this.trainings = data;
  });
console.log(this.trainings);

但是日志是空的 console log of object

这就是它在database 中的样子

有人知道如何处理吗?

【问题讨论】:

  • 控制台中有任何错误吗?网络请求在您的浏览器开发人员工具中看起来如何?
  • 由于它是异步调用,因此您的 console.log 首先执行并返回空。但你可以在你的订阅中使用 console.log 看看
  • 在 subscribe 中使用 console.log 即 subscribe(data => { console.log(data); this.trainings = data });

标签: angular


【解决方案1】:

在订阅中使用 console.log

ngOnInit(): void {
   this.calendarService.getAllTrainings().subscribe(data => {
    console.log(this.trainings);
    this.trainings = data;
  });

由于调用 api 是一项异步任务,因此需要一些时间才能获得响应,如果您在订阅者外部使用 console.log,则控制流将不会等待 api 调用,从而导致打印 this.trainings 变量的初始值,

如果你在订阅者内部调用它,控制流将在 api 响应完成后执行 console.log,因此 console.log 将打印值。

【讨论】:

    猜你喜欢
    • 2020-08-16
    • 1970-01-01
    • 2020-09-19
    • 2021-04-30
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多