-3

I'm trying to pull JSON files from the web and I am doing something wrong. Here is my code:

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

import { Observable } from 'rxjs';


@Injectable({
  providedIn: 'root'
})
export class PullanaliticsService {
  theUrl: string = 'https://jsonplaceholder.typicode.com/post';
  res = [];
  private httpClient: HttpClient;
  constructor() { }


  httpGetAsync()
  {
      var t = this.httpClient.get(this.theUrl).subscribe((res) => {
        console.log(res);
      });

      return t

}

(I changed this.theUrl to a page everyone can view)

I am getting the error:

DashboardComponent.html:4 ERROR TypeError: Cannot read property 'get' of undefined
    at `PullanaliticsService.push../src/app/pullanalitics.service.ts.PullanaliticsService.httpGetAsync (pullanalitics.service.ts:22)`

which sounds like the URL is not working but I cannot figure out why.

baj9032
  • 2,414
  • 3
  • 22
  • 40
Vladimir_314159
  • 1,457
  • 1
  • 9
  • 21
  • That's not telling you the URL isn't working, it's telling you that you haven't correctly injected the `HttpClient` into your service. Read the docs: https://angular.io/guide/http. – jonrsharpe Jun 20 '18 at 15:41
  • 1
    You could tell from the dev tools network tab that the network request isn't even being attempted here. @jonrsharpe is correct in saying that in this particular error it doesn't matter whether the url is returning data. – Chris Farmer Jun 20 '18 at 15:48

2 Answers2

3

Here you have to initialize the http in your constructor as follows :

constructor(private httpClient: HttpClient) { }

eduPeeth
  • 1,840
  • 13
  • 21
1

Your service should have the httpClient injected into it. You declare it, but you never set its value in your code. You can let angular set that value for you by supplying the http client in the constructor.

@Injectable({
  providedIn: 'root'
})
export class PullanaliticsService {
  theUrl: string = 'https://jsonplaceholder.typicode.com/post';
  res = [];
  constructor(private httpClient: HttpClient) { }


  httpGetAsync() {
      return this.httpClient.get(this.theUrl);
  }
}

Letting angular do that in the constructor is just a shortcut for:

export class PullanaliticsService {
  private httpClient: HttpClient;
  constructor(_httpClient: HttpClient) {
    this.httpClient = _httpClient;
  }
}
Chris Farmer
  • 24,974
  • 34
  • 121
  • 164
  • 1
    The behaviour you describe at the end is *still* letting Angular inject it, that's TypeScript syntax ("parameter property" shorthand) not an Angular feature. – jonrsharpe Jun 20 '18 at 15:50
  • That is true. I intended that the focus be on the fact that angular was the thing doing the injecting. – Chris Farmer Jun 20 '18 at 15:55