2017-10-09 24 views
0

我有此組件TypeError:this。 <class>。 <function>不是函數

export class Component1Component implements OnInit { 

public greetings: string =""; 

constructor(private greeter: Greeter) { } 

ngOnInit() { 
    this.greetings = this.greeter.sayHello(); 
} 

} 

Greeter類被定義爲

export class Greeter{ 
    private hello_greetings = "Hello"; 
    constructor(){} 
    public sayHello():string { 
    return this.hello_grittings; 
    } 
} 

Greeter類由工廠提供:

export function GreeterFactory():Greeter { return new Greeter(); } 

@NgModule({ 
    providers: [        
     { provide: Greeter,   
      useFactory: GreeterFactory, 
      multi: true      
     } 
    ] 
}) 

當的Component1是加載,我得到這個錯誤:

AppComponent.html:1 ERROR TypeError: this.greeter.sayHello is not a function at Component1Component.ngOnInit (component1.component.ts:36)

如果我在OnInit方法打印this.greeter,我得到這樣的輸出:

[{"hello_greetings":"Hello"}]

所以,它看起來像類被正確注射,但由於某種原因沒有在被發現的方法運行。

整個項目可以發現提前here

感謝您的幫助

回答

1

您需要從服務提供商處刪除multi: true。該標誌表示該對象將作爲數組注入。這正是你在控制檯輸出中看到的:[{"hello_greetings":"Hello"}](請注意[])。

+0

愚蠢的錯誤!謝謝! – pablochacin

+0

@pablochacin不客氣!很高興我能幫上忙 :) –

0

您正在爲Greeter服務提供選項multiple: true,因此允許多個服務實例並將它們作爲實例數組進行角注入。

您必須將multi: true更改爲multi: false或省略它。

0

這是因爲greeterGreeter實例的數組,以便類型是正確的,應該被注入像

constructor(@Inject(Greeter) private greeter: Greeter[]) { } 

由於the reference狀態,

multi?: boolean

If true, then injector returns an array of instances. This is useful to allow multiple providers spread across many files to provide configuration information to a common token.

如果它應該是是多供應商,那麼應該在其中一個實例上調用該方法,即this.greeter[0].sayHello()。如果不是,則不應指定multi

相關問題