我正在使用 Angular2 创建一个简单的 Web 应用程序。 该应用程序必须调用 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。
也许我犯了一个错误,但我不知道是什么以及在哪里。一个想法?
最佳答案
好吧,我自己找到了解决方案。 问题是我的 localhost API 没有启用 CORS。但 Angular2 没有返回一个错误来告知这一点。
干净的代码: 天气服务
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)
);
}
}
天气组件:
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);
}
}
关于 Angular 2 : API call return an error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39815478/