Angular 4 get method not able to fetch data

1.8k views Asked by At

I am a newbie to angular 4 . I was trying to implement routing with the use of Observables . The link I had specified for url to be used in getting data from http.get request doesnt seems to work and returns an error .

Following is the code for my service "productService.ts":

import { Injectable } from '@angular/core';
import { IProducts } from './productsInterface';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch'; 
import 'rxjs/add/operator/do';   


@Injectable()
export class ProductService {
    private urlOfService = './products.json';

    constructor(private http: HttpClient){}

    getProducts():Observable<IProducts[]>{
        return this.http.get<IProducts[]>(this.urlOfService)
                        .do(data=>console.log('The data recieved' + JSON.stringify(data)))
                        .catch(this.handleError);
    }
    private handleError(err:HttpErrorResponse){
        console.log(err.message);
        return Observable.throw(err.message);
    }

}

And the component in which the service is to be used is as shown below : "ProductListComponent.ts"

import { Component, OnInit, Injectable } from '@angular/core';
import { FormsModule }from '@angular/forms';
import {IProducts} from  './productsInterface';
import {ProductService} from  './productService';

@Injectable()

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css']
})

export class ProductListComponent implements OnInit {
  errorMessage: any;
  products: any;




  constructor(private _useProductService : ProductService) { console.log(_useProductService); }

  ngOnInit() {
    console.log('Inside ngOnInit');
    this._useProductService.getProducts().subscribe(
      products=>{this.products= products; console.log(products)},error=>this.errorMessage =<any>error
    );
  }

  pageTitle:string = "Official Merchandise";
  imageHeight:number= 40;
  imageWidth:number = 40;

  showImage: boolean = false;

  filterList :string = "Cart";
}

I have a products.json file which is to be utilized in the service ( Data has to come from this file ) All the 3 files ( products.json , productListComponent.ts & productService.ts ) are in the same folder .

But still Angular shows ,error 404 file not found(for products.json) . GET call doesnt works , the rest of the application works just fine

I have tried modifying my file path accordingly but still its not working for me . Also I had given a path to the products.json file in angular-cli.json under assets array ,still doesnt works .

Kindly advise on the same ... Thanks !

1

There are 1 answers

0
harold_mean2 On

My app is also a shopping cart application, and below is my service to get all the products and my code maybe different from yours.

getProducts() {
  return this._http.get('http://localhost:3000/product').map(response => {
    const data = response.json().obj;   // from server route - the obj your are returning.
    console.log(data) /* see if you get any data here..*/
    let objs = this.returnProducts(data);
    this.products = objs;
    return objs;
  })
  .catch(error => Observable.throw(error.json()));
}

If you do not get any data in the console, more likely you need to debug your server code. I also re-factor it because my app is growing.

returnProducts(data: any[]){
  let objs: any[] = [];     
  for (let i = 0; i < data.length; i++) {
    let product = new Product(data[i].title, data[i].imageUrl, 
      data[i].description, data[i].filter, data[i].price, 
      data[i].brand, data[i].color, 
  }
}

Below shows this code is working.. enter image description here