[英]Angular 6:services with providedIn: 'root' returns empty object in component
My service located in src/core/services/api.service.ts
我的服务位于
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 {}
但是我得到了一个像
ApiService {}
这样的空对象
So it is returning an object and that means that the service is initialized correctly, instead of console.log(this.api)
;所以它返回一个对象,这意味着服务被正确初始化,而不是
console.log(this.api)
; try console.log(this.api.test())
, you should see hello from services
in the console.尝试
console.log(this.api.test())
,您应该会在控制台中看到hello from services
。
Same thing happened for me in Angular 8.我在 Angular 8 中也发生了同样的事情。
I added public in front of the function then it started working:我在函数前面添加了 public 然后它开始工作:
public test()
I had some unused imports in the service.我在服务中有一些未使用的导入。
Removing those imports and restarting ng serve worked for me.删除这些导入并重新启动ng serve对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.