【问题标题】:Angular2: API call return an errorAngular2:API调用返回错误
【发布时间】:2017-02-10 10:42:26
【问题描述】:

我正在使用 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);
              }
            );
  }

}

问题是这个服务总是返回错误:

错误:Object { _body:错误,状态:0,ok:false,statusText:“”,标题:对象,类型:3,url:null }

但在 Mozilla Firefox 开发工具中,调用 API 并返回带有状态码 200 的 JSON。

也许我犯了一个错误,但我不知道是什么和在哪里。一个想法?

【问题讨论】:

  • 我刚刚测试了您的代码,它在我的情况下按预期工作。我刚刚导入了import 'rxjs/Rx'
  • @micronyks 像这样:import 'rxjs/Rx'; import 'rxjs/add/operator/toPromise'; ?
  • 是的......正是......
  • @micronyks 这对我没有任何改变,我遇到了同样的错误。

标签: angular typescript


【解决方案1】:

好的,我自己找到了解决方案。 问题是我的 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)
            );
  }
}

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);    
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 2015-10-28
    相关资源
    最近更新 更多