使用HttpClient从typescript中的json文件中获取数据



我正在构建一个angular应用程序。

我试图通过json文件在资产目录中获取一些图像文件的位置。在json文件中提到了图像的位置。但是在运行应用程序后,我得到错误404,并说它找不到我的json文件。

浏览器显示这个错误信息。

Object { headers: {…}, status: 404, statusText: "Not Found", url: "http://localhost:4200/landingPageData.json", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost:4200/landingPageData.json: 404 Not Found"

My specifications:

Angular CLI: 15.0.5节点:18.10.0包管理器:npm 8.19.2节点:v18.10.0操作系统:linux x64

我有一个json文件'landingPageData。在我的angular应用的/src目录下。文件中的数据如下所示。

{
"photos":[
{
"img": "assets/images/landing1.jpg",
"description": "Learn 100 english words effectively in 1 day!"
},
{
"img": "assets/images/landing2.jpg",
"description": "What you will learn"
},
{
"img": "assets/images/landing3.jpg",
"description": "Join today!"
}
]
}

在我的app.component.ts文件中,我试图仅从json数据中获取图像文件的位置,并将其存储到数组landingScreens

import { Component, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http'
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
@Injectable()
export class AppComponent {
public landingScreens: any;
constructor(private http:HttpClient){
this.http.get('./landingPageData.json').subscribe((response) => {
this.landingScreens = response;
})
}
}

然后在模板app.component.html文件中,我显示了这些图像,假设我有这些图像的位置。

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

我试图不导入json数据,因为在未来我将使用api来获取响应,这将是json格式。我是不是把订阅部分弄乱了?或者给出正确的目录位置?

landingPageData。Json文件在/src文件夹,app.component.ts文件在*/src/app *文件夹。图片位于assets/images文件夹中。

我已经浏览了stackoverflow的所有相关答案,但大多数答案都是非常旧的angular版本,或者答案告诉他们要导入json文件。

我没有先把<mat-card>标签放在<mat-tab>中。之后我放了landingPageData。assets文件夹中的Json文件。

@JanatbekOrozaly建议的这个链接有帮助


app.component.ts

export class AppComponent{
landingScreens: any = [];
constructor(private httpClient:HttpClient){
this.httpClient.get("assets/landingPageData.json").subscribe(data => {
this.landingScreens = data;
})
}
}

app.component.html

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

最新更新