2016-10-02 61 views
0

我正在使用Angular2創建一個簡單的Web應用程序。 此應用程序必須調用API來獲取一些數據。Angular2:API調用返回錯誤

我創建了一個服務和組件,如官方教程中所示。

服務:

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); 
       } 
      ); 
    } 

} 

的問題是,該服務始終返回錯誤:

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

但在Mozilla Firefox瀏覽器的開發工具,API被稱爲與狀態代碼返回JSON 200.

也許我犯了一個錯誤,但我沒有看到什麼和在哪裏。一個主意 ?

+0

我只是測試你的代碼和它的作品如預期在我的案件。我剛剛導入了'import'rxjs/Rx'' – micronyks

+0

@micronyks像這樣:'import'rxjs/Rx'; import'rxjs/add/operator/toPromise';'? – Nowis

+0

是的......確切地說..... – micronyks

回答

1

好的,我自己找到了解決方案。 問題是我的localhost API沒有啓用CORS。但是Angular2沒有返回一個錯誤通知這件事。

乾淨代碼: 的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);  
    } 
} 
相關問題