Angular 2 : API call return an error

标签 angular typescript

我正在使用 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/

相关文章:

angular - Ionic 显示等于该值的数据

angular - 如何在库中声明/包含导入的 scss 文件夹,以便可以在应用程序的 scss 文件中调用 @import?

angular - 如何访问 Angular 组件上的 TemplateRef?

angular - ionic 4 : "Loading Controller" dismiss() is called before present() which will keep spinner without dismissing

typescript - 'XXX' 没有提供签名 'new (): XXX' 的匹配项

reactjs - 如何为浏览器编译 typescript

angular - firestore 和他的 children 一起拿到文件

javascript - 如何在angular 5中以编程方式转换html元素

javascript - Angular 2 ngFor 值(数字)总结

Angular 2 OpaqueToken 与 Angular 4 InjectionToken