簡體   English   中英

angular2 http.get()不向服務器發送請求

[英]angular2 http.get() doesn't send request to the server

我正試圖從我的角度應用程序對localhost執行一個get請求到我的api。 但由於某種原因,角度http客戶端似乎不執行get請求。

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

EXCEPTION:未捕獲(在promise中):TypeError:無法讀取未定義的屬性'subscribe'

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

附加控制台 在此輸入圖像描述 在此輸入圖像描述

也許您應該嘗試回溯(或轉發)問題:

從...開始:

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

問題可能出在標題或插入的URL或任何地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM