2016-10-04 53 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或任何地方。