我正在使用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);
}
);
}
}问题是,此服务总是返回一个错误:
错误:对象{ _body:错误,状态: 0,ok: false,statusText:"",headers: Object,type: 3,url: null }
但是在Mozilla开发工具中,API被调用并返回状态代码200的JSON。
也许我犯了个错误,但我不知道是什么,什么地方。一个主意?
发布于 2016-10-02 10:38:59
好吧,我自己找到了解决办法。问题是我的本地主机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);
}
}https://stackoverflow.com/questions/39815478
复制相似问题