api - angular2 http.get() 不向服务器发送请求

标签 api http angular get angular2-services

我正在尝试从我的 Angular 应用程序对本地主机上的 api 执行获取请求。但由于某种原因,angular http 客户端似乎没有执行 get 请求。

我可以在我的 api 服务器上看到没有发出 get 请求。这是导致错误的原因。该 API 运行良好,我尝试执行 curl 并得到了预期的结果。

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

最佳答案

也许您应该尝试回溯(或正向)问题:

开始于:

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

问题可能出在标题或插入的 url 或任何地方。

关于api - angular2 http.get() 不向服务器发送请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39852261/

相关文章:

api - 使用 C 模块覆盖内置 Redis 命令

ios - NSTimer,当我回到 ViewController 时不会启动

node.js - 如何在 tfs 构建管道中设置 Angular 7 的环境

javascript - Angular 2 - 在使用 "Upgrade Adapter"升级时是否可以使用新路由器

api - 时间范围的 Twitter API 推文

python - 如何更正关于单独 Python 文件的 "ModuleNotFoundError' "?

docker - 在 IntelliJ 上连接到 Docker 时出现错误 "Status 400: Client sent an HTTP request to an HTTPS server."

c++ - 如何创建简单的带有 boost 的 HTTP 服务器,能够接收数据编辑和共享?

angular - Ionic 3 - 过滤复杂数组

json - Jenkins 多分支插件和远程 API