Issues with Angular2 http.get() returning 404 errors consistently

I'm encountering an issue while attempting to load dummy JSON data from a file using angular2 http.get method. It appears that the method is unable to retrieve the data, consistently returning a 404 status code for resource not available. Below is the code snippet I am using:

const obs: Observable<any> = this.http.get('http://localhost:4200/assets/mock-json/cashback.json')
    .map((res: Response) => {
      console.log('***********',res.json());
      res.json(); })
    .do((res) => this.loadedCB = res);
 if (this.loadedCB) {
     return Observable.of(this.loadedCB);
 }

Interestingly, when I manually enter the URL http://localhost:4200/assets/mock-json/cashback.json in my browser, it successfully retrieves the data. It's puzzling why it doesn't work with http.get().

Answer №1

If you're encountering this issue, it could be due to not subscribing to the observable, preventing it from executing and therefore not receiving any results (you can verify this in the network tab of a web inspector).

To resolve this, make sure to subscribe to the observable to initiate its execution.

Here is an example:

export class AppComponent implements OnInit {
  loadedCB: any;

  constructor(public http: Http) {
  }

  ngOnInit() {
    this.tryAndLoad();
  }

  tryAndLoad() {
    this.load().subscribe((res: any) => {
      this.loadedCB = res;
      if (this.loadedCB) {
        console.log(this.loadedCB);
        return Observable.of(this.loadedCB);
      }
    });
  }

  load() {
    return this.http.get('http://localhost:4200/assets/mock-json/cashback.json')
      .map((res: Response) => {
        console.log('***********', res);
        return res.json();
      })
  }
}

This code snippet properly returns a result that you can manipulate as needed. Since an observable is returned, additional actions can be performed (though not demonstrated in this demo).

https://i.sstatic.net/BGTWV.png

https://i.sstatic.net/4wEJM.png

Don't forget to add import 'rxjs/Rx'; at the beginning of your page to avoid any errors related to this.http.get(...).map

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

Is it more efficient for the component to retrieve data from storage or to be provided with the data

Within my Angular application (version 10), I utilize data that is unique to each request. To make certain business decisions, I extract information from a portion of the URL domain name. In the early stages of development of my application, I extracted t ...

Unleashing the power of TypeScript in combination with svelte and d3

Currently, I am facing an issue with TypeScript regarding data types. Specifically, I am working on a Svelte component for the x-axis of a d3 visualization. In this component, I receive the xScale as a property from the parent component like this: <XAix ...

Having trouble reading properties of undefined (specifically 'listen') during testing with Jest, Supertest, Express, Typescript

Issue: While running jest and supertest, I encounter an error before it even gets to the tests I have defined. The server works fine when using the start script, and the app is clearly defined. However, when running the test script, the app becomes undefi ...

Unable to locate a compatible version for caniuse-lite with the specified range of ^1.0.30001349

I encountered an error while running npm install: npm ERR! code ETARGET npm ERR! notarget No matching version found for caniuse-lite@^1.0.30001349. npm ERR! notarget In most cases you or one of your dependencies are requesting npm ERR! notarget a package v ...

Guide for making a JSON request to a Ruby on Rails application

I need to send JSON parameters from an HTML page using a text area. For example, the JSON parameter should be in this format: {"name": "test", "description":"test", "price":100} However, when sending it to Rails, it is received as {"{'name' : &a ...

Tips for deserializing SQLAlchemy JSON data into Decimal values with Flask-SQLAlchemy

My code successfully serializes an object containing Decimal values and stores them in JSON format in my PostgreSQL database. I found a helpful post on Stack Overflow that guided me through the process. I'm using Flask-SQLAlchemy, so I created a custo ...

Expanding declaration files in TypeScript to include third-party libraries

Is there a way to customize third-party declaration files? For instance, I am looking to enhance Context from @types/koa by adding a new field (resource) to it. I attempted the following: // global.d.ts declare namespace koa { interface Context { ...

What is the correct way to invoke a function from an external JavaScript file using TypeScript?

We are currently experimenting with incorporating Typescript and Webpack into our existing AngularJS project. While I have managed to generate the webpack bundle, we are facing an issue at runtime where the program is unable to locate certain functions in ...

The $http patch request is failing to transmit data to the server

Recently, I started utilizing AngularJS to create a CRUD functionality using Laravel and AngularJS. I have implemented a function that serves the purpose of both updating and saving data. Here is my function code: $scope.save = function (modalstate, id) ...

Should an HTML canvas in Angular be classified as a Component or a Service?

I have a basic drawing application that uses an MVC framework in TypeScript, and I am looking to migrate it to Angular. The current setup includes a Model for data handling, a View for rendering shapes on the canvas, and a Controller to manage interactio ...

What is the best way to convert a BigDecimal to a decimal format within a JSON response when using JAX

While utilizing Tomee 8 as my application server, I am encountering an issue when my REST service returns a BigDecimal. This is the structure of my service: import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs. ...

Using Angular's UI Typeahead feature in conjunction with the `$http.get`

Seeking assistance with retrieving data from a local server using JSON (not JSONP) and presenting it in a typeahead via Angular UI bootstrap and Angular. Successfully implemented timeout() and jsonp based on examples found, confirming that promises are fun ...

What is the best way to showcase an element within an array that matches a particular value or character?

I have obtained a JSON array from hxxp://best1st.info/Moviedb/json.php?m=tt2015381&o=json Here is a snippet of the array output: . and so on . . [STORYLINE] => On planet Earth in 1988, young Peter Quill ( ) sits in the waiting room of a hospital. ...

Having trouble getting useFieldArray to work with Material UI Select component

I am currently working on implementing a dynamic Select field using Material UI and react-hook-form. While the useFieldArray works perfectly with TextField, I am facing issues when trying to use it with Select. What is not functioning properly: The defau ...

Combining GroupBy and OrderBy Features in Ionic2 using Angular2

Is there a way to organize an array of data by hostname (link) and sort it by date data in Angular2? I'm currently using an API that returns the following array: this.items = [ {name: "banana", link: "https://wiki.com/what-ever/mmmmmmmmm/mdmdm", ...

Angular 2 and TypeScript: Mastering Checkbox Data Binding

Below is the HTML view in which user roles are checked. I want to bind a table of modified user roles using the actualizeRoles() method. How can I achieve this? <md-accordion class="example-headers-align"> <md-expansion-panel hideToggle=" ...

Ionic retrieves a filtered array of JSON data

Having difficulty filtering the array to retrieve values where the parent id matches the id that is provided. For instance, if an ID of 1 is sent, it should result in a new array with 3 items. An ID of 4 will return 1 item, and an ID of 5 will also return ...

PHP Code: How to Retrieve JSON from a Remote URL

Looking for some help with decoding a JSON file. Here's the link to the file: I've been trying to decode it using PHP like this: $json = file_get_contents('http://www.jeewanaryal.com/angryQuiz/eighties/json/eighties.json'); $data = j ...

Click to load additional data until the list has reached its full length

<ng-container *ngFor="let item of itemList | slice:0:3"> <mat-checkbox>{{item}}</mat-checkbox> </ng-container> <div> <button id="loadMore">Load More</button> </div> I wo ...

Integrate a dictionary into a JSON object using Python Flask

While I am relatively new to coding and working on my own small projects, I have come across an issue that has been troubling me for the past few days. Essentially, what I am trying to do is append my dictionary to a list and then dump it into a JSON file ...