I've been working on an angular application recently.
My current challenge is fetching the locations of image files from the asset directory using a json file. The json file contains references to where the images are stored. However, upon running the application, I encounter a 404 error indicating that the json file cannot be found.
The specific error message displayed in the browser is as follows:
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"
Here are my specifications :
Angular CLI: 15.0.5 Node: 18.10.0 Package Manager: npm 8.19.2 Node : v18.10.0 OS: linux x64
The 'landingPageData.json' file exists in the /src directory of my angular application and its content is structured like this:
{
"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!"
}
]
}
In my app.component.ts file, I am attempting to extract only the image file locations from the json data and store them in an Array called 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;
})
}
}
Then in the template app.component.html file, I display these images assuming that their locations are available.
//
//
<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>
//
//
I'm avoiding importing the json data directly because I plan to switch to using an API for fetching responses in json format in the future. Could my issue be with how I've implemented the subscribe function or the directory location specified?
The landingPageData.json file is located within the /src folder while the app.component.ts file is in */src/app* directory. Additionally, the images are stored in the assets/images folder.
Although I've researched solutions on stackoverflow, most of them pertain to older versions of Angular or suggest importing the json file, which I'm trying to avoid.