Nowis
Nowis

Reputation: 590

Angular2: API call return an error

I'm using Angular2 to create a simple web application. This application must call an API to get some datas.

I created a Service and a Component, as seen in the official tutorial.

The service:

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import 'rxjs/add/operator/toPromise';

@Injectable()
export class WeatherService {

  private url : string = 'http://127.0.0.1:1337/weather';

  constructor(private http: Http) {
    console.log('Weather URL API:', this.url);
  }

  public getWeather() {
    return  this.http
            .get(this.url)
            .toPromise()
            .then(
              (response) => {
                console.log('response:',response);
              },
              (error) => {
                console.log('Error:',error);
              }
            );
  }

}

The problem is that this service always return an error:

Error: Object { _body: error, status: 0, ok: false, statusText: "", headers: Object, type: 3, url: null }

But in the Mozilla Firefox development tools, the API is called and return JSON with status code 200.

Maybe I made a mistake, but I don't see what and where. An idea ?

Upvotes: 2

Views: 2010

Answers (1)

Nowis
Nowis

Reputation: 590

Ok, I found the solution by myself. The problem was my localhost API does not had CORS enabled. But Angular2 no returned an error who inform about this.

The clean code: WeatherService

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import 'rxjs/add/operator/toPromise';

@Injectable()
export class WeatherService {

  private url : string = 'http://127.0.0.1:1337/weather';

  constructor(private http: Http) {
  }

  public getWeather() {
    return  this.http
            .get(this.url)
            .toPromise()
            .then(
              res => res.json(),
              err => console.log('Error:',err)
            );
  }
}

WeatherComponet:

import { Component, OnInit } from '@angular/core';
import { WeatherService } from '../weather.service';

@Component({
  selector: 'app-weather',
  templateUrl: './weather.component.html',
  styleUrls: ['./weather.component.css'],
  providers: [WeatherService]
})
export class WeatherComponent implements OnInit {
  datas;

  constructor(private weatherService: WeatherService) {
  }

  ngOnInit() {
    this.weatherService.getWeather()
    .then(data => this.datas = data);    
  }
}

Upvotes: 2

Related Questions