0

I'm trying to display a list with data fetched from a local json file. Here is how my service looks so far.

category.service.ts

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';

@Injectable()
export class CategoryService {
  constructor(private _http: Http) { }

  getCategories() {
    return this._http.get('api/categories.json')
      .map((response: Response) => response.json())
      .do(data => console.log('All; ' + JSON.stringify(data)))
      .catch(this.handleError);
  }

  private handleError(error: Response) {
    console.log(error);
    return Observable.throw(error.json().error || 'Server error');
  }
}

here is how the Category Menu component where I inject it looks so far

import { Component, OnInit } from '@angular/core';
import { CategoryService } from '../category.service';

@Component({
  selector: 'app-category-menu',
  templateUrl: './category-menu.component.html',
  styleUrls: ['./category-menu.component.css']
})
export class CategoryMenuComponent implements OnInit {
  errorMessage: string;
  commerceName= `El baratón`;
  categoryName = `Bebidas`;
  categories: any = 'Not assigned yet';
  hasMenu?= true;

  constructor(private _categoryService: CategoryService) { }


  ngOnInit() {
    return this._categoryService.getCategories()
      .subscribe(
        categories => this.categories = categories,
        error => this.errorMessage = error
      );
  }

}

Now, the error I am getting in the console is a 404. For this project I have used the CLI version 1.0 and the categories.json file inside of the src/api/categories.json folder.

What am I doing wrong here?

1
  • How do you post code block with upper "Run code snippet" function? Commented Apr 17, 2017 at 3:53

1 Answer 1

2

move your api/categories.json to assets folder, then change url to

return this._http.get('/assets/api/categories.json')
Sign up to request clarification or add additional context in comments.

3 Comments

This solved it. Thanks Now I don't understand why the previous approach did not work. Could you provide some further explanation?
Angular CLI will serve assets folder, which have all resources, it does not serve all project content like lite-server.
Of course once the app has a live backend (testing against local .json files is a good idea) the request will be made to a server and it may not be the same server that hosts the Angular app. If you are not sure, it might be better to use a lightweight json server such as npm:json-server which hosts .json files from an arbitrary folder and runs in a separate process. It also permits reading and writing them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.