Search code examples
angulartypescriptangular2-services

Service `http` get method doesn't return success or error


I am writing a service that returns array of cars. My service method dont return sucess or error. The folder assets is in the same directory as `app folder.

This is my service method:

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Car} from '../../../domain/car';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class CarService {

  constructor(private http: Http) {
  }
    getCarsMedium(): Promise<Car[]> {
       console.log("call1");
       return this.http.get('assets/data/cars-medium.json')
       .toPromise()
       .then(res => {
          console.log("sucess1" + res);
          console.log("sucess2" + res.json());
          return res.json().data as Car[]
          })
       .catch(error => {
          console.log("error");
          console.error(error);
       });
   }

}

I call it as:

import {Component, OnInit} from '@angular/core';
import {Car} from "../../../domain/car";
import {CarService} from "./car.service";

@Component({
  moduleId: module.id,
  templateUrl: './car.component.html',
  styleUrls: ['./car.component.css']
})

export class CarComponent implements OnInit {
  cars: Car[];

  constructor(private carService: CarService) {
  }

  ngOnInit() {
    console.log("call2");
    this.carService.getCarsMedium().then(function (cars) {
      cars => this.cars = cars;
      console.log(cars)
    });
  }
}

This is how my json looks like:

{"data":[
    {"vin":"a1653d4d","year":1998, "brand":"VW","color":"White"},
    {"vin":"a1653d4w","year":1999, "brand":"VV","color":"White"}
]}

Entity class:

export interface Car {
  vin?;
  year?;
  brand?;
  color?;
}

EDIT: getCarsMedium() dont return sucess or error. console output: call2 call1


Solution

  • I found the reason: I have jwt-authentication in project http://jasonwatmore.com/post/2016/08/16/angular-2-jwt-authentication-example-tutorial][1] - it blocked my request