Accessing JSON file with TypeScript HttpClient

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.

Answer №1

I initially forgot to place the <mat-card> tag inside the <mat-tab>. Once I corrected that, I moved the landingPageData.json file into the assets folder.

This helpful resource was suggested by @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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing a series of sequential HTTP calls in Angular can be achieved by chaining

Is there a way to create a function that can make HTTP calls one after the other, allowing me to use the response from the first call in the second call? For example, retrieving the user's IP address from the first call and then using that IP address ...

Encountering challenges with synchronous calls in AngularJS

Two service calls need to be executed synchronously in a specific order, using promises. However, the execution is not happening as intended. Controller: vm.nominationSVC.zipping(vm.fileSelected, vm.selectedCategoryId). then(function (respons ...

Making an Angular POST request and then navigating to a new component

Hello, I am a beginner in Angular and struggling to make my code work. It seems like a basic functionality issue that I can't seem to figure out. My goal is to send a post request to my .NET core API to register a user, and once that is done, navigat ...

Exploring the capabilities of the VSCode Volar extension in a project utilizing Vue 2, Nuxt, Typescript, and the @nuxtjs composition-api

Trying to set up the Volar VSCode extension for a NuxtJS / Typescript project and facing two issues in .vue file templates. Followed the installation guide for Vue 2 and Typescript, and enabled Take Over mode. Solved some codebase issues with the extensio ...

What is the correct way to invoke a function that accepts a combination of specific string values when all I have is a regular string?

Within the TypeScript function declaration provided below, the parameter type alignment consists of unioned literals. function printText(s: string, alignment: "left" | "right" | "center") { // ... } As per the documentation ...

Encountering errors when incorporating a node.js server into an Angular project

I successfully have my angular app up and running. Now, the next step is to create some RESTful services. My plan was to integrate a node.js server within the same angular app for just a couple of APIs. I created a file at src\server\server.ts wi ...

Ensure that Angular resolver holds off until all images are loaded

Is there a way to make the resolver wait for images from the API before displaying the page in Angular? Currently, it displays the page first and then attempts to retrieve the post images. @Injectable() export class DataResolverService implements Resolv ...

When deploying an Angular 4 application in IIS, the command router.navigate(['/']) may not function as expected when the browser is refreshed

app.component.ts @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers: [BureauApiService,BureauStateWorkflowComponent,CommondataApiService] }) export class ...

Web Development Woes: AngularJS and Angular-Material Failing to Render HTML Even with Object in $scope

I have been searching extensively for a solution to this issue without any luck. Any assistance in this matter would be highly appreciated. Key Details: Using angular-material tabs When an item is selected from a dropdown, a request is sent to a firebas ...

Exploring the process of introducing a new property to an existing type using d.ts in Typescript

Within my src/router.ts file, I have the following code: export function resetRouter() { router.matcher = createRouter().matcher // Property 'matcher' does not exist on type 'VueRouter'. Did you mean 'match'? } In an ...

Applying Type Constraints in Typescript Arrays Based on Other Values

Uncertain about how to phrase this inquiry. I have a specific situation where an object is involved. Key1 represents the name, while key2 stands for options. The type of options is determined by the value of the name. The existing solution works fine than ...

There are no imports in index.js and there is no systemjs configuration set up

After creating a fresh Angular project using ng new some-name, I noticed that the generated index.html file does not include any <script> tags and there is no SystemJS configuration either. Is this the expected behavior? I was anticipating the CLI ...

Leveraging @ContentChildren in Angular 2 to sort through a component's contents

I am currently working on implementing a search component that can trigger a search(term: string) function on specific child components. If the search on the child fails, the function will return null; otherwise, it will return a reference to the child. M ...

showcasing JSON content on an HTML page using Angular version 4

I am dealing with JSON data that I can successfully read and access in the console. However, I am having trouble displaying this data on my HTML page. Every time I try to read it, I encounter an error message stating that it cannot read property of NewData ...

Please provide me with the steps to relocate the src/pages/api folder to src/ in a Next.js project

When working with Next.js, I am interested in relocating the src/pages/api directory to be located under src/, much like how it is done in blitz.js. In this case, the directory structure would look something like this: src |- pages |- api Unfortunately, I ...

How to apply animation in Angular 2 to a single element within an *ngFor loop

Is it possible to apply animation to only one element when using *ngFor in Angular? Currently, the animation applies to all elements in the cycle, but I want to target only one element. How can I achieve this? .............................................. ...

What is the best way to retrieve property names that are not nullable from a type?

I am seeking to create a custom mapped conditional type in TypeScript that will allow me to extract property names from a type, while accounting for properties that can potentially have a value of null. For example: interface Person { name: string a ...

Adding numbers together in TypeScript is a simple task that can be done using the

While it may appear to be a simple question, my attempts to find relevant results have been fruitless due to Google search being case insensitive. Consider the following code snippet: items[5] = "5\,5" totalAmount: number = 5 totalAmount = totalAmou ...

A guide on passing properties to tabs in Ionic React

Having trouble passing an array as a prop to a tab and encountering a confusing error. Below is the code snippet: <IonRouterOutlet> <Route path="/tab1" render={props => (<Tab1 loanProps={loans} />)} /> /> &l ...

In Next.js, a peculiar issue arises when getServerSideProps receives a query stringified object that appears as "[Object object]"

Summary: query: { token: '[object Object]' }, params: { token: '[object Object]' } The folder structure of my pages is as follows: +---catalog | | index.tsx | | products.tsx | | | \---[slug] | index.tsx | ...