2017-03-31 38 views
0

我有了在ngOnInit方法什麼是錯的這個操作符被未定義

this.businessTypesService.get() 
     .subscribe((businessTypes: string[]) => { 
      _.each(businessTypes, 
       (businessType: string) => { 
        this.businessTypes.push({ label: businessType, value: businessType }); 
       }); 
     }); 

現在我有這個相同類型的塊的10倍的選項每個加載不同的降列出瞭如下的組件。除了調用哪個服務以及哪個數組將它推入結果之外,每個方法都是相同的,所以我想將其重構爲單個方法,以便我可以將代碼更改爲這樣的代碼。

this.loadReferenceList(this.businessTypesService.get, this.businessTypes); 

和新loadReferenceList方法看起來像這樣

loadReferenceList(loadMethod:() => Observable<string[]>, lookupList: SelectItem[]): any { 
    loadMethod() 
     .subscribe(((items: string[]) => { 
      _.each(items, 
       (item: string) => { 
        lookupList.push({ label: item, value: item }); 
       }); 
     })); 
} 

服務類中的每一個看起來像這樣

import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 

import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/observable/of'; 
import 'rxjs/add/operator/map'; 

@Injectable() 
export class BusinessUnitsService { 

    get(): Observable<string[]> { 
     return Observable.of(this.getData()); 
    } 

    constructor(private readonly http: Http) { } 

    getData(): string[] { 
     return [ 
      'Beverage', 
      'Food', 
      'Beverage & Food', 
      'Promo Pack' 
     ]; 
    } 

} 

現在它只是硬編碼的數據,但將改變稍後使用Http降低實際值。

問題是this.getdata()行失敗,說這是未定義的。我不明白爲什麼當我改變它被稱爲這樣的時候,這將是不確定的。

******** Answer ************ 我做了以下更改以使其基於以下答案工作 loadReferenceList方法已更改爲外觀喜歡這個。基本上爲服務添加了一個參數,以便我可以引用這個應該是什麼,然後添加.bind方法來提供方法範圍。

loadReferenceList(loadMethod:() => Observable<string[]>, service: any, lookupList: SelectItem[]): any { 
    const method = loadMethod.bind(service); 

    method() 
     .subscribe(((items: string[]) => { 
      _.each(items, 
       (item: string) => { 
        lookupList.push({ label: item, value: item }); 
       }); 
     })); 
} 

回答

1

您可能需要您獲得()綁定到你的對象,即

loadReferenceList(this.businessTypesService.get.bind(this.businessTypesServices), ...)

,或者您需要定義抽象接口的所有服務,並通過對象作爲是

loadReferenceList(service: AbstractService, ...) { service.get() } 所有服務需要實現此接口

+0

這不起作用,因爲這是未定義的。所以this.getData錯誤,因此this.getData.bind也會出錯。您是否嘗試過 –

+0

或者您在評論這個評論? –

+0

兩者。我知道這是行不通的,我只是爲了確保 –

0

I made a live simple version of what you're doing

我在使用Observable.of(...)時遇到了問題。它工作時,我使用Observable.create(...)和新的Observable(...)。

幾乎所有與rxjs有關的事情,我都使用這樣的plunkr來測試。讓我知道它是否有幫助?

+0

我沒有看到你在你的例子中使用這個操作符。無論如何,我嘗試着用新的observable來做,但是當我做observer.next(this.getData())時我仍然沒有定義。 –

+0

我的歉意,當我嵌入它時,plunkr被重置。 – Everett

+0

修改了鏈接 – Everett

相關問題