2017-08-24 78 views
1

我有利用价值提供这个组件:角2喷油器错误“无法读取的未定义的属性‘实例’”

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 undefinedError as shown in the console

如果重要,我的看法是一个简单的<h1>{{title}}</h1>

我做错了什么?

回答

1

不要使用注射器,只是导入“进样”的装饰,并使用像所谓

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; 
    } 
} 
+0

你的回答可以解决问题,但为什么不是我的工作?我的程序有什么问题? –

+0

注入器用于注入某些事物的实例,而不是原始值。未分配给变量的原始字符串只是一个字符串,而不是变量或类的实例。 – diopside

+0

如果在组件之外声明 export const currency =''; 然后在您指定的提供商行 提供:currency(without the quotes) 但我不确定 – diopside

相关问题