2017-11-11 112 views
1

我有一個組件,比如說MyComponent。我已經注入了一個服務到這個組件,比如MyService。如何在注入時將參數傳遞給一個支持服務?

當在另一個組件(比如ParentComponent)中使用'MyComponent'時,它通過模板將一些參數傳遞給'MyComponent'。注入'MyComponent'的'MyService'需要這個模板參數。如何在注入服務時將它傳遞給服務?

現在我寫了一個特殊的函數,它將在'MyComponent'的init()函數中調用。我不知道這是否正確。

這裏是一個粗略的代碼示例:

父組件/ template.hbs:

// some html 
{{my-component myOptions=parentOptions}} 
// some html 

我組分/ component.js:

export default Component.extend({ 
// some js 
myService: inject.service(), 
init() { 
    this._super(...arguments); 
    get(this, 'myService').passDownMyArguments(get(this, 'myOptions')); 
}, 
// some js again 
}) 

我想知道我可以在注入時將'myOptions'傳遞給服務,而不是調用服務中的另一個函數。

回答

0

不,您注入時無法將值傳遞給服務。你正在做的是處理給定你的設置的最佳方式。但是一個問題是:你的服務應該放在包含的組件中嗎?

1

我想你不能。 正如您可以從組件的生命週期https://guides.emberjs.com/v2.6.0/components/the-component-lifecycle/看到, 組件將從模板接收參數初始化後只, 這樣你就可以在下一週期掛鉤這樣的傳遞參數:

... 
myService: inject.service(), 
didReceiveAttrs() { 
    this.get('myService').myFunction(this.get('myOptions')); 
} 
相關問題