Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to perform a get request to my api on localhost from my angular app. But for some reason the angular http client seems not to perform the get request.

I can see on my api server that no get request was made. And this is causing the error. The api is working fine I tried doing a curl and I get the expected results.

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

Attached the console enter image description here enter image description here

like image 278
Salma Hamed Avatar asked Oct 19 '22 00:10

Salma Hamed


1 Answers

Maybe you should try to backtrack (or forward-track) the problem:

start with:

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

The problem might be in the headers or in the interpolated url or anywhere.

like image 153
Tobias Gassmann Avatar answered Oct 21 '22 06:10

Tobias Gassmann