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

Angular使用HttpClient获取JSON文件出现404错误的问题求助

解决Angular中JSON文件请求404的问题

核心原因

Angular CLI默认仅会将src/assets目录下的文件打包到最终构建产物中,你放在src根目录的landingPageData.json不会被纳入静态资源,因此HTTP请求会返回404。

解决方案

方案一:将JSON文件移至assets目录(规范做法)

  1. 把landingPageData.json移动到src/assets目录下
  2. 修改app.component.ts中的请求路径,同时注意要取JSON里的photos数组(否则模板循环会报错):
import { Component } from '@angular/core';
import {HttpClient} from '@angular/common/http'
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  public landingScreens: any[] = []; // 初始化空数组避免undefined报错
  constructor(private http:HttpClient){
    this.http.get('assets/landingPageData.json')
      .pipe(
        catchError(error => {
          console.error('加载数据失败:', error);
          return throwError(() => error);
        })
      )
      .subscribe((response: any) => {
        this.landingScreens = response.photos;
      })
  }
}

方案二:修改angular.json配置打包src根目录的JSON

如果不想移动文件,可修改Angular构建配置,让CLI将src根目录的JSON文件复制到产物中:

  1. 打开项目根目录的angular.json
  2. 找到projects -> [你的项目名] -> architect -> build -> options -> assets数组,添加如下配置:
"assets": [
  "src/favicon.ico",
  "src/assets",
  "src/landingPageData.json" // 添加这一行
]
  1. 保存后重启开发服务,原请求路径./landingPageData.json即可正常访问。

模板代码修复

你的模板存在两个问题:

  1. mat-card不在mat-tab的内容区域内,导致卡片不会显示在About标签页中
  2. 推荐用属性绑定[src]代替插值表达式,避免潜在的XSS风险

修正后的模板:

<mat-tab-group>
    <mat-tab label="About">
        <mat-card *ngFor="let img of landingScreens; let i=index">
            <img mat-card-image [src]="img.img" [alt]="img.description">
        </mat-card>
    </mat-tab>
    <mat-tab label="Courses"></mat-tab>
    <mat-tab label="Contact"></mat-tab>
</mat-tab-group>

额外注意点

  • 组件不需要添加@Injectable()装饰器,该装饰器仅用于服务类
  • 始终添加错误处理逻辑,避免请求失败时出现未捕获异常

内容的提问来源于stack exchange,提问作者Shahir Abdullah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 09:50:17