2016-10-04 16 views
5

Próbuję wykonać żądanie pobierania do mojego api na localhost z mojej aplikacji kątowej. Ale z jakiegoś powodu kątowy klient HTTP wydaje się nie realizować żądania pobierania.angular2 http.get() nie wysyła żądania do serwera

Widzę na moim serwerze api, że nie otrzymano prośby o pobranie. I to powoduje błąd. Api działa dobrze Próbowałem robić curl i otrzymuję oczekiwane rezultaty.

EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'subscribe' of undefined

api.service

import { Injectable } from '@angular/core'; 
import { Headers, Http, Response, URLSearchParams, RequestOptions } from '@angular/http'; 
import { Observable } from 'rxjs/Rx'; 

@Injectable() 
export class ApiService { 
    headers: Headers = new Headers({ 
     'Accept': 'application/json', 
     'Content-Type': 'application/json' 
    }); 

    api_url: string = 'http://localhost:5001'; 

    constructor(private http: Http) { } 

    private getJson(response: Response) { 
     return response.json().results; 
    } 

    checkForError(response: Response): Response { 
     if (response.status >= 200 && response.status < 300) { 
      return response; 
     } else { 
      var error = new Error(response.statusText); 
      error['response'] = response; 
      Observable.throw(error); 
     } 
    } 

    get(path: string, params: URLSearchParams): Observable<any> { 
     return this.http 
      .get(`${this.api_url}${path}/`, { headers: this.headers }) 
      .map(this.checkForError) 
      .catch(err => Observable.throw(err)) 
      .map(this.getJson); 
    } 

api.component.ts

import { Component, OnInit } from "@angular/core"; 
import { ApiService } from './api.service'; 

@Component({ 
    selector: 'item', 
    templateUrl: './item.component.html' 
}) 
export class ItemComponent implements OnInit { 
    private itemData; 
    private errorAlert; 

    constructor(private apiService: ApiService) {} 

     ngOnInit() { 
      this.apiService.get('/items').subscribe(
       result => this.itemData = result, 
       error => this.errorAlert = {msg: error, type: 'danger', closable: true}, 
     ); 
     } 
} 

załączeniu konsolę enter image description here enter image description here

+0

W 'checkForError' powinien pojawić się' return' przed 'Observable.throw (error)', ale wydaje się to niezwiązane z twoim komunikatem o błędzie. 'map (getJson)' powinno być 'map (this.getJson)'. –

+1

Obserwowalny nie robi niczego przed wywołaniem funkcji 'subscribe()'. Ponieważ 'subscribe()' nie działa, nie może być żądania. –

+0

Podaj zrzut ekranu z zakładki sieci narzędzi deweloperskich –

Odpowiedz

3

Może powinieneś spróbować cofnąć (lub forward-track) problem:

początek z:

this.http.get('/my/hardcoded/url').subscribe(); 

może być problem w nagłówkach lub w interpolowana URL lub gdziekolwiek.

Powiązane problemy