Angular2 http.get () does not send a request to the server

I am trying to execute a get request to api on localhost from my angular application. But for some reason, the angular http client does not seem to execute the get request.

I can see on my api server that the receive request was not received. And that causes an error. Api works fine, I tried to make curl, and I get the expected results.

EXCEPTION: Unavailable (in promise): TypeError: Unable to read subscribe property 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}, ); } } 

Attaching a Console enter image description here enter image description here

+5
source share
1 answer

Perhaps you should try to cancel (or forward) the problem:

start with:

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

The problem may be in the headers or in the interpolated URL or anywhere.

+3
source

Source: https://habr.com/ru/post/1257690/


All Articles