Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient returns "Cannot read property 'get' of Undefined" [Angular 7]

I'm trying to create a simple API service in Angular 7 that I can include in any component that needs it. However, whenever I call it from a component, I get an error. For example, if from within my component I call ApiService.read('/public/flavorsofcandy/') I get:

ERROR TypeError: Cannot read property 'get' of undefined

Now, I'm unsure why this is, but I feel it's something simple and silly. However, nowhere could I find why this is happening. I feel this is due to me not fully understanding concepts related to classes and whatnot, instead of Angular 7 itself.

api.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ApiService {

    private baseUrl = "http://localhost:11000/";
    private http: HttpClient;

    public create = (req:string, options?:any) => {
        this.http.post(this.baseUrl+req, options)
        .subscribe(response=> {return response})
    }

    public read = (req:string, options?:any) => {
        this.http.get(this.baseUrl+req,options)
        .subscribe(response=> {return response})
    }

    public update = (req:string, options?:any) => {
        this.http.put(this.baseUrl+req, options)
        .subscribe(response=> {return response})
    }

    public delete = (req:string, options?:any) => {
        this.http.delete(this.baseUrl+req, options)
        .subscribe(response=> {return response})
    }

};


mycomponent.ts

import { Component, OnInit } from '@angular/core';
import { ApiService as api} from '../../scripts/api.service';


@Component({
  selector: 'MyComponent ',
  templateUrl: './MyComponent.html',
  styleUrls: ['./MyComponent.scss'],
})
export class MyComponent implements OnInit {
  public flavorsList: any;

  constructor() { }

  ngOnInit() {
    this.getFlavors()
  }

  getFlavors() {
    this.flavorsList = api.read('/public/flavorsofcandy/')
  }

}

like image 446
invot Avatar asked Oct 18 '25 14:10

invot


2 Answers

Your HttpClient is not defined. In the line of code private http: HttpClient; you declare it, but never give it a value so it remains as undefined.

The HttpClient class is Injectable, so we can inject it in a conscructor for your ApiService like so:

constructor(private http: HttpClient) {}

And now we can access it anywhere in this service by calling this.http.get(someUrl).subscribe(ex => {});

like image 130
JamieT Avatar answered Oct 22 '25 04:10

JamieT


You're not injecting the HttpClient. You need to use the constructor to inject it. See https://angular.io/guide/dependency-injection. Don't forget to import HttpClientModule in your AppModule.

like image 26
Will Alexander Avatar answered Oct 22 '25 04:10

Will Alexander