2016-10-04 80 views
5

我想從我的角度應用程序執行獲取請求到本地主機上的api。但由於某些原因,角度http客戶端似乎不執行獲取請求。angular2 http.get()不發送請求到服務器

我可以在我的api服務器上看到沒有獲取請求。這是導致錯誤。 api工作正常我試着做一個捲曲,我得到了預期的結果。

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

附控制檯 enter image description here enter image description here

+0

在'checkForError'中'Observable.throw(error)'之前應該有一個'return',但這與你的錯誤信息似乎無關。 'map(getJson)'應該是'map(this.getJson)'。 –

+1

在調用subscribe()之前,observable不做任何事情。因爲'subscribe()'失敗,所以不能有請求。 –

+0

從開發工具的網絡選項卡提供一些截圖 –

回答

3

也許你應該嘗試原路返回(或前軌道)的問題:

開始:

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

問題可能是在標題或內插URL或任何地方。