Angular 6:services with providedIn: 'root' returns empty object in component

Viewed 1196

My service located in src/core/services/api.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor() { }

  test() {
    console.log('hello from services');
  }
}

I am trying to invoke this service from a component which in another module.

home.component.ts

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

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

  constructor(private api: ApiService) { }

  ngOnInit() {
    console.log(this.api);
  }

}

But I am getting an empty object like this ApiService {}

3 Answers

So it is returning an object and that means that the service is initialized correctly, instead of console.log(this.api); try console.log(this.api.test()), you should see hello from services in the console.

Same thing happened for me in Angular 8.

I added public in front of the function then it started working:

public test()

I had some unused imports in the service.

Removing those imports and restarting ng serve worked for me.

Related