FakeEmpire
FakeEmpire

Reputation: 798

Http call as service in Angular

I am brand new to Angular and I am attempting to make a simple http request for data. How do I access this data in my component? I am getting the error 'Cannot read property 'get' of undefined'

data.service.ts

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

@Injectable()
export class FetchData {

    private url: string = 'https://jsonplaceholder.typicode.com/users'
    constructor(private http: HttpClient){}

    get(){
        return this.http.get(this.url).subscribe(data => {
            console.log(data)
        })
    }

}

table.component.ts

import { FetchData } from './datatable.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-datatable',
  templateUrl: './datatable.component.html',
  styleUrls: ['./datatable.component.css']
})
export class DatatableComponent implements OnInit {

  Data: FetchData

  constructor() { }

  ngOnInit() {
    this.Data.get()
  }

}

Upvotes: 1

Views: 416

Answers (2)

Danny908
Danny908

Reputation: 531

You need to "Inject" the service in your component and also make the subscription in your component.

In your service you should "map" your response.

import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import 'rxjs/add/operator/map';

    @Injectable()
    export class FetchData {

        private url: string = 'https://jsonplaceholder.typicode.com/users'
        constructor(private http: HttpClient){}

        get(){
            return this.http.get(this.url).map(data => {
              return data.json();
            })
        }

    }

Your component:

import { FetchData } from './datatable.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-datatable',
  templateUrl: './datatable.component.html',
  styleUrls: ['./datatable.component.css']
})
export class DatatableComponent implements OnInit {

  constructor(private fetchDataService: FetchData) { }

  ngOnInit() {
    this.fetchDataService.get().subscribe(res => {
       console.log(response);
    });
  }

}

Upvotes: 1

Fateh Mohamed
Fateh Mohamed

Reputation: 21377

try this:

export class DatatableComponent implements OnInit {
constructor(private dataService: FetchData) { }

ngOnInit() {
  this.dataService.get()
}}

Upvotes: 0

Related Questions