Having difficulty accessing JSON data from the assets folder in Angular

What I Desire:: In my project, I have a configuration file that contains URLs in a .json format. This file is stored in the asset folder. Instead of loading environments.prod or .ts files, I want to load this json configuration file and utilize it to run my application.

My Approach:

 Here is the content of my json file located in the asset folder:

{
    "baseUrl": "https://jsonplaceholder.typicode.com/",
    "baseUrl2": "https://reqres.in/api/users"
}

I then created a ConfigServiceService.ts to handle this configuration file.

public _config: Object;

  constructor(public http:Http) { }

  getData(){
    debugger;
    return this.http.get("./assets/config.json").pipe(map(res =>  res.json()));
  }

After setting up the config service, I created a ServiceProviderService.ts to make use of the service file.

configData:any;

  constructor(public http:Http,public config:ConfigServiceService) {

   }

  jsonData(){
    debugger;
    return this.configData;
  }

  ngOnInit(){
    debugger;
    this.config.getData().subscribe(res =>{
      console.log(res);
      this.configData = res;
    });


  }

Next, I implemented the logic in the app.component.ts.

 title = 'sample';
  constructor(public serv :ServiceProviderService){
    this.serv.jsonData();
  }

However, I am facing an issue where I am unable to retrieve the json data. If I move the logic from ngOnInit in ServiceProviderService.ts file to the constructor, I receive 'undefined'.

Note: If there are multiple URLs in the configuration file, each URL needs to be assigned to a separate service file. How can I accomplish this?

Answer №1

If you want to access the assets folder, ensure that the file angular.json contains a reference in the following location:

architect --> build -->options should point to the directory where the file is stored:

 "assets": [
              "src/favicon.ico",
              "src/assets"
            ],

Answer №2

If you try using an absolute URL, it should work properly

Give this code a shot:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class DataService {

  constructor(private http: HttpClient) { }

  fetchData() {
    return this.http.get('/assets/data.json');
  }

}

Check out a Demo StackBlitz Example for reference.

Answer №3

Within the realm of Angular, it's crucial to understand that only components possess lifecycle hooks such as ngOnInit, ngOnDestroy, and so on. Services, on the other hand, lack these hooks but rely on their constructor instead.

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

Refreshing div content based on dropdown selection without reloading the page

I am currently working on implementing a dynamic dropdown feature that will update text content on a webpage without needing to refresh the entire page. The updated text will be fetched from a PHP function which receives input from the dropdown selection. ...

Issues encountered with custom themes in ngx-chips (ng2) tag input component configuration

I have searched extensively for a question that has already been answered, but to no avail. I carefully reviewed the description page and followed all instructions provided. Within my Scss folder where custom bootstrap is defined, I proceeded to create a ...

Encountered an error while parsing JSON data in Angular 6 and PHP: SyntaxError - Unexpected token < at the beginning of the JSON string in the JSON.parse

Presented below is my PHP class: <?php //header('Access-Control-Allow-Headers: *'); //header('Content-Type: application/json'); //header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS'); erro ...

Google's geolocation.getCurrentPosition function fails to function properly on mobile devices after the page is refreshed

I recently created a website that utilizes the Google Geolocation JavaScript API along with the vue2-google-maps package. Here is a snippet of the relevant code: `geolocate () { var self = this this.loading = true navig ...

While the AWS CodePipeline is executing the script, an error is appearing in the log. Please address this issue and resolve it

This is the content of buildspec.yml: version: 0.2 phases: install: commands: - npm install -g typescript pre_build: commands: - echo Installing source NPM dependencies... - npm install build: commands: - echo Bui ...

Sencha Touch's actionable column

Does Sencha Touch have an xtype: actioncolumn similar to ExtJS 4.1 for column configuration? If not, what alternatives does Sencha Touch offer? ...

remaining aligned after sending the form

Can someone help me figure out why my code is not submitting data to the database without redirecting the page? $('#saving').on('click', function() { var fname = $('#fname').val(); var lname = $('#lname ...

React typescript - Error: Type 'boolean' is not compatible with the expected type

Check out this demo This is a simple React application built with Typescript. Currently, I am experimenting with React's Context API. I have set up a context named ThemeContext which holds basic theme styling values to be used across different comp ...

Unable to upload the file using AJAX

Here is my AJAX request where I am attempting to send form data to a PHP page and display messages accordingly. The problem I'm encountering is that when using serialize() method in AJAX, my file data is not being posted. As a result, the send.php scr ...

Posting data to an HTML file with a foreign key matching the input value in Express.js

My discussion platform features topics and comments. Each comment has its own unique topic_id. Currently, I am able to post comments for the initial topic, but encountering issues when adding new comments for other topics. I am looking for guidance on effi ...

Strange Node.js: I always avoid utilizing `require()`, yet encountered an unexpected error

For more information on this particular issue, please refer to this link It's quite puzzling as I haven't used the require() function in my code, yet I'm receiving an error telling me not to use it. How odd! The problematic code snippet i ...

The collection of elements from another component in React is failing to display in a list format

I am encountering an issue while trying to map an array of objects that I imported from a different component. The error message displayed is: Warning: Each child in a list should have a unique "key" prop. along with the following error details: Pleas ...

Unable to locate module in Vue.js when using browserify

When trying to use almost every npm package with vue.js 1.0, I keep encountering this frustrating error: { Error: Cannot find module '!!./../../../node_modules/css-loader/index.js!./../../../node_modules/vue-loader/lib/style-rewriter.js!./../../../no ...

Designing a personalized look for a property with Styled-System

Styled-System offers various props related to css grid: I have a suggestion for a new prop, gridWrap. My idea is to allow users to adjust the auto-fit value using the gridWrap prop. Here's the base CSS code: grid-template-columns: repeat(auto-fit, mi ...

Is there a way to successfully submit a form in PHP once it has been validated using JavaScript?

I'm interested in creating a register/login system. I've set up a form in Register.php and handled the validation part in JavaScript, but I'm encountering an issue where no values are being sent to the database upon clicking submit. Registe ...

React, facing the challenge of preserving stored data in localStorage while accounting for the impact of useEffect upon

Seeking some assistance with the useEffect() hook in my Taking Notes App. I've set up two separate useEffects to ensure data persistence: one for when the page first loads or refreshes, and another for when a new note is added. I've added some l ...

Challenges when sending a POST request to Google Cloud Vision using JavaScript

My aim is to send a simple POST request to Google Cloud Vision API using javascript and jquery. When testing in Chrome, I encounter a 400 error in the console without any additional information for debugging. I'm hoping that someone with experience in ...

Is it better to have Angular and Laravel as separate applications or should Laravel serve the Angular app?

I have a new project in the works, aiming to create a large SAAS application. Although I come from a CakePHP background, I've decided to use Laravel and Angular for this venture. As I navigate through unfamiliar territory with these technologies, I a ...

Utilize Launchdarkly in React by incorporating it through a custom function instead of enclosing it within

Currently, I am adhering to the guidelines outlined by launchdarkly. Following the documentation, I utilized the following code snippet: import { asyncWithLDProvider } from 'launchdarkly-react-client-sdk'; (async () => { const LDProvider = a ...

Trouble linking JavaScript and CSS files in an Express App

Could someone assist me in understanding what is causing my code to malfunction? Why is it that my javascript and css files do not execute when the server sends the index.html file to the browser? I have a simple setup with an html page, javascript file, ...