Angular 6:具有provedInIn的服务:“ root”在组件中返回空对象

时间:2018-11-14 09:31:58

标签: javascript angular service dependency-injection

我的服务位于src/core/services/api.service.ts

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

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

  constructor() { }

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

我正在尝试从另一个模块中的组件调用此服务。

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);
  }

}

但是我得到一个像ApiService {}

的空对象

3 个答案:

答案 0 :(得分:1)

因此它正在返回一个对象,这意味着服务已正确初始化,而不是private void add(Vertex source,Vertex target){ if(!checkEdgeExist(graph,source,target)) source.addEdge(target).property(WEIGHT,1.0); else { Edge e = getEdgeBetweenTwoVertices(graph,source,target); source.edges(Direction.OUT).forEachRemaining(edge -> { if(edge.inVertex().equals(target)) edge.property(WEIGHT,(double)e.property(WEIGHT).value()+1); }); private static boolean checkEdgeExist(TinkerGraph graph,Vertex source,Vertex target){ return graph.traversal().V(source).outE().filter(p -> p.get().inVertex().equals(target)).hasNext(); } ;尝试console.log(this.api),您应该在控制台中看到console.log(this.api.test())

答案 1 :(得分:0)

我在Angular 8中发生了同样的事情。

我在函数之前添加了public,然后它开始工作:

public test()

答案 2 :(得分:0)

我在服务中有一些未使用的进口商品。

删除这些导入并重新启动 ng服务对我来说是有效的。