angular - Angular2: فراخوانی 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);
              }
            );
  }

}

مشکل این است که این سرویس همیشه یک خطا برمیگرداند:

خطا: شیء { _body: خطا، status: 0، ok: نادرست، statusText: "", headers: شیء، type: 3، url: تهی }

اما در ابزارهای توسعه موزیلا فایرفاکس، API فراخوانی میشود و JSON با کد وضعیت ۲۰۰ برمیگرداند.

شاید من اشتباه کردهام، اما نمیبینم چه چیزی و کجا. نظری داری؟

پاسخ شماره ۱

باشه، خودم راه حل را پیدا کردم. مشکل این بود که 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)
            );
  }
}

کامپوننت آب و هوا:

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