Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 {}

like image 432
shellakkshellu Avatar asked Aug 13 '26 17:08

shellakkshellu


1 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.

like image 60
Mac_W Avatar answered Aug 16 '26 06:08

Mac_W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!