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.
也许我犯了一个错误,但我没有看到什么和在哪里。一个主意 ?
我只是测试你的代码和它的作品如预期在我的案件。我刚刚导入了'import'rxjs/Rx'' – micronyks
@micronyks像这样:'import'rxjs/Rx'; import'rxjs/add/operator/toPromise';'? – Nowis
是的......确切地说..... – micronyks