Fetch data from a JSON file using a URL

Having trouble accessing data from a JSON file via URL. Everything seems to be in order but nothing is working, and I'm at a loss for how to troubleshoot it.

service

export class JsonService {


  public getMenuData(): Observable<any> {
    
    return new Observable((observer) => {
      this.http.get('https://demored.ddns.net:50443/demored/path_image/menu.json').subscribe((response)=> {
        observer.next(response);
        observer.complete();
      });
    });
  }

Component

ngOnInit() {

    this.getJson();
    
  }

  getJson(){
    this.jsonService.getMenuData().toPromise().then(data => {
      this.menuJson = data;
      console.log("Menu from json file ",this.menuJson);
    }).catch((err) => {
      console.log('error in fetching data',err);
    });
  }

Answer №1

When you need to retrieve data from a service, you can use the GET request and convert it into a promise with toPromise(). Within any component, simply call the service method defined in the constructor as this.serviceJson(), then resolve the promise using .then() or .catch().

export class JsonService {
  
  getMenuData(): Promise<any> {
   return this.http.get<any>('https://demored.ddns.net:50443/demored/path_image/menu.json').toPromise()
  }

component

  ngOnInit() {

    this.getJson();
    
  }

  async getJson(){
   await this.jsonService.getMenuData().then(data => {
      this.menuJson = data;
      console.log("Menu from json file ",this.menuJson);
    }).catch((err) => {
      console.log('error in fetching data',err);
    });
  }

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

What is the process for destructuring an interface in TypeScript?

My request is as follows: const listCompartmentsRequest: identity.requests.ListCompartmentsRequest = { compartmentId: id, compartmentIdInSubtree: true, } I want to shorten the long line identity.requests.ListCompartmentsRequest. I'm looking for ...

Implement real-time word counting in Angular as users type

I am looking to monitor word count in real-time as a user enters text into a textarea field If the word limit of 100 is exceeded, further typing should be restricted I aim to display the word count dynamically as the user types wordCounter() This functi ...

Is there a way to incorporate a loading spinner into a MaterialUI DataTable without having to specify a fixed height for the parent component?

Currently, I am using a MaterialUI DataTable with the following setup: <div style = {{height: 300}}> <DataGrid loading={true} getRowHeight={() => "auto"} getEstimatedRowHeight={() => 250} ...

Inaccuracies arise when trying to interpret a JSON string as an object

I have tried various solutions found on stack overflow, but none of them seem to work for me. I am attempting to call an asmx web service using jQuery. Below is my code: <script type="text/javascript"> $(document).ready(function () { ...

Express app issues error: JSON response not returned properly - Uncaught SyntaxError: Unexpected end of data

I'm in need of some fresh perspective. My goal is to have a basic Express app return JSON data (in this case, a Firebase token) every time a request is made to it. Here's the code for my Express server: app.get('/validate', function ...

Error: The reference to "global" is undefined and was not caught in the promise

After successfully running my project, I encountered an issue upon installing the aws-sdk package from here. Despite trying to find solutions online, I have been unable to resolve this problem. The error message I am facing is: core.js:1673 ERROR Error ...

Display the toggle button for expanding/collapsing text only when the length of the string exceeds 50 characters

Is there a way to only show a "read more/less" button in a table if the content exceeds 50 characters? The table contains a mix of content, some short announcements with about 10 characters and others with over 100. <div class="col"> <span ng-c ...

Typescript issues arise when a library lacks any available types for download

I attempted to incorporate the react-keydown library into my project, but encountered the following error: Could not find a declaration file for module 'react-keydown'. '/home/path../node_modules/react-keydown/dist/index.js' implicitl ...

How can I effectively store nested JSON data in a SQL Server database?

I am currently dealing with a nested JSON dataset that needs to be uploaded into SQL SERVER 2012. This JSON data consists of two main sections - one for columns and the other for rows. My task is to map the values from the rows section into their correspon ...

Accessing information necessitates two separate subscriptions

I am posting this inquiry in order to enhance my understanding. Below is an excerpt from my service: export class HomeService { private generalstatistics = new ReplaySubject<object>(); constructor( private http: HttpClient ) { this ...

What are the steps to collapse React state in a comments section?

Here is the data I have: { "currentUser": { "image": { "png": "/src/assets/images/avatars/image-juliusomo.png", "webp": "/src/assets/images/avatars/image-juliusomo.webp" }, ...

Testing the Angular component with service: An error occurred while trying to access the `diagnosticData` property as it was found to be undefined

Seeking guidance on angular testing as a beginner. I have encountered an issue where my component is not receiving the values during testing, even though the app functions correctly. Can someone assist me with this? I have shared the service, JSON object, ...

What is the reason behind the lack of covariance in an interface when using a type of T[keyof T]?

I'm attempting to enable type covariance so that Type<Cat> can be treated as a Type<Animal>, for instance, treating a list of Cats as a list of Animals. However, using the type T[keyof T] in a method within the Type interface seems to hind ...

Angular2 Error: ngClass used in a Host component, "is not recognized as a valid native property"

Is it feasible to utilize the "ngClass" directive within the host for a component or directive? @Component({ selector: 'custom', template: `<div [ngClass]="classMap"></div> // It works <ng-content></ng-content&g ...

Incorporating JSON Data into an Android App

I am facing a situation where I have a JSON file containing contacts that need to be transformed into objects for display in a ListView. However, I am struggling with accessing the contacts.json file. I am unsure of the correct location for this file so th ...

How to specify a single kind of JavaScript object using Typescript

Let's say we have an object structured as follows: const obj = [ { createdAt: "2022-10-25T08:06:29.392Z", updatedAt: "2022-10-25T08:06:29.392Z"}, { createdAt: "2022-10-25T08:06:29.392Z", animal: "cat"} ] We ...

What is the most effective way to structure JSON data for an API in Go using a struct?

As a newcomer to Go, I am exploring ways to simplify the normalization of JSON data received from the front-end (JS) to my API. To ensure that I correctly handle types when creating a variable from my model.Expense struct, I currently dump the payload into ...

Include a JSON attribute containing the URL of a specific object found within the response data

I am currently working on an API project (without the use of any gems) and I am hoping to enhance the responses it provides. Specifically, When the API consumer requests a list of objects: the API will reply with a list of objects displaying only sele ...

The FormControl is currently presenting ",required(control)" within its value field

Upon loading my form, the default values in the input fields are set to: ,required(control) { return isEmptyInputValue(control.value) ? { 'required': true } : null; } The template structure of my form is as follows: <form [formG ...

Ensuring the structure of a model in a JSON array with Angular

While working with Angular, I have a model defined as follows: export interface MyModel { id: number; content: string; } In one of my services, I fetch JSON data that matches the attributes of MyModel. Here's an example: function getMyModel ...