角度2喷油器错误"无法读取属性'实例'未定义"

时间:2017-08-24 20:27:46

标签: angular angular2-services

我使用值提供程序使用此组件:

import { Component, OnInit, Injector } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [{
    provide: "currency",
    useValue : "dollar"
  }]
})
export class AppComponent implements OnInit  {
  ngOnInit(): void {

  }

title = "app works";


constructor(private injector: Injector){
 this.title = "Currency is: "+ injector.get("currency");
 }
}

当我运行程序时,进样器会抛出一个错误," Cannot read property 'instance' of undefined" Error as shown in the console

如果重要,我的观点很简单<h1>{{title}}</h1>

我做错了什么?

1 个答案:

答案 0 :(得分:1)

不要使用Injector,只需导入'Inject'装饰器并使用如此 -

import { Component, OnInit, Inject } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [{
     provide: "currency",
     useValue : "dollar"
  }]
})
export class AppComponent implements OnInit  {
  ngOnInit(): void {

  }

  title = "app works";


  constructor(@Inject("currency") private currency){
     this.title = "Currency is: "+ currency;
  }
}