2016-10-02 58 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);  
    } 
} 
相关问题