2016-12-17 295 views
0

我試圖從組件傳遞一些值給服務構造函數。 我試圖傳遞參數的對象。 我的代碼是:如何將參數傳遞給構造函數的服務

constructor(public af: AngularFire, public userData: UserData ,param: boolean) { 
    this.smartTableData = this.af.database.list('events/' + this.userData.user.uid + '/contacts',{ 
    preserveSnapshot: param, //this param should be taken from component 
     query: { 
     orderByChild: 'tableNumber' 

     } 
    }); 

和我的組件:

import {LocalDataSource} from 'ng2-smart-table'; 

@Component({ 
    selector: 'basic-tables', 
    encapsulation: ViewEncapsulation.None, 
    styles: [require('./smartTables.scss')], 
    template: require('./smartTables.html') 
}) 
export class SmartTables { 
    constructor(protected service: SmartTablesService) { 
     this.service.smartTableData.subscribe((data) => { 
      console.log(data); 
      this.source.load(data); 
     }); 
     } 
+0

但我服務,只能由一個的conf –

+0

它可以處理取決於什麼'datatopass'是這樣的發球2個組件,但不同的。通常它可以是'setData(datatopass)'方法。但問題在於,服務是屬於它的注入器中的單例,並且將'datatopass'設置爲兩個組件同時會導致不可預知的結果。這個問題應該澄清'SmartTablesService'中發生的事情。 – estus

+0

我更新我的帖子,需要的值是param它只是布爾值。一個組件需要它作爲true和其他false。 2個組件不相同的頁面。2組件更新Firebase列表。 –

回答

1

這是不方便做服務的構造函數的請求,因爲服務實例是電流注射器內單。 af.database.list只在第一次注射時被調用一次,而param也只會被注入一次。

另一個問題是DI在組件構造函數之前發生。

應該

constructor(public af: AngularFire, public userData: UserData) {} 

getData(param: boolean) { 
    return this.af.database.list(...); 
} 
相關問題