You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中无法从Service向Component传递API请求数据的问题

问题根源

HTTP请求是异步操作,你调用getAllLuoghi()后立刻给cards赋值时,请求还未完成,serviceLuoghi.luoghi仍是初始的空数组,所以最终cards为空。

解决方案

下面提供两种常用的修复方式,按需选择:

方式一:让Service返回Observable,组件订阅赋值

修改Service的getAllLuoghi方法,直接返回请求的Observable,由组件订阅后获取数据:

// luoghi.service.ts
import { Observable, catchError, tap, throwError } from 'rxjs';

// 可去掉类内的luoghi数组,或保留用于缓存
getAllLuoghi(): Observable<any[]> {
  return this.http.get<any[]>("http://localhost:9595/oota-reg/api/luoghi/all").pipe(
    tap(response => console.log(response)),
    catchError(error => {
      console.log("Something went wrong..", error);
      return throwError(() => error);
    })
  );
}

修改Home组件,订阅Observable并赋值给cards:

// home.component.ts
private serviceLuoghi: LuoghiServiceService = inject(LuoghiServiceService);
public cards: any[] = [];

ngOnInit(): void {
  this.serviceLuoghi.getAllLuoghi().subscribe({
    next: (response) => {
      this.cards = response;
      console.log(this.cards);
    },
    error: (error) => {
      // 按需处理错误逻辑
    }
  });
}

方式二:用BehaviorSubject实现响应式数据共享

适合多个组件需要同步同一份数据的场景,通过Subject发布数据变化:

// luoghi.service.ts
import { BehaviorSubject, Observable } from 'rxjs';

private luoghiSubject = new BehaviorSubject<any[]>([]);
// 对外暴露只读的Observable
public luoghi$ = this.luoghiSubject.asObservable();

getAllLuoghi() {
  this.http.get<any[]>("http://localhost:9595/oota-reg/api/luoghi/all").subscribe({
    next: (response) => {
      console.log(response);
      // 发布新数据
      this.luoghiSubject.next(response);
    },
    error: (error) => {
      console.log("Something went wrong..", error);
    }
  });
}

修改Home组件,订阅数据变化:

// home.component.ts
private serviceLuoghi: LuoghiServiceService = inject(LuoghiServiceService);
public cards: any[] = [];

ngOnInit(): void {
  this.serviceLuoghi.getAllLuoghi();
  // 订阅数据更新
  this.serviceLuoghi.luoghi$.subscribe(data => {
    this.cards = data;
    console.log(this.cards);
  });
}
额外修复:Card组件接收数据

当前模板中<app-card>没有传递数据,即使cards有值,Card组件也无法展示内容,需修改:

<!-- home.component.html -->
<div class="flex justify-center flex-wrap gap-5">
    @for (item of cards; track item.id) { <!-- 优先用唯一标识(如item.id)代替$index -->
        <app-card [item]="item"></app-card> <!-- 传递数据给Card组件 -->
    }@empty {
        <p>none</p>
    }
</div>

在Card组件中定义输入属性接收数据:

// card.component.ts
import { Input } from '@angular/core';

@Component({
  selector: 'app-card',
  templateUrl: './card.component.html',
  styleUrls: ['./card.component.css']
})
export class CardComponent {
  @Input() item: any; // 接收Home组件传递的数据
}

内容的提问来源于stack exchange,提问作者Andrea Crinella

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 18:45:57