2017-06-22 63 views
4
private customer: Subject<Object> = new BehaviorSubject<Object>(null); 

setCustomer(id, accountClassCode) { 
    this.customer.next({'id': id, 'accountClassCode': accountClassCode}); 
} 

getCustomer() { 
    return this.customer.asObservable(); 
} 

我正在使用這部分代碼,但遇到無法找到空id的錯誤。有沒有解決方案來獲得非空的初始值?行爲主體初始值null?

+1

你嘗試一個空的對象?新的BehaviorSubject ({}); –

+0

即時發生錯誤提供的參數不匹配調用目標的任何簽名。 – None

+1

有一個解決方案。如果您不需要初始值,請勿使用BehaviorSubject。 – estus

回答

13

BehaviorSubject目的是提供初始值。它可以是null或其他任何東西。如果不能提供有效的初始值(當用戶ID尚不知道時),則不應使用它。

ReplaySubject(1)提供了一個類似的行爲(發佈訂閱時的最後一個值),但沒有初始值,直到它被設置爲next

這可能應該是

private customer: Subject<Object> = new ReplaySubject<Object>(1); 
1

嘗試通過這種方式構建服務:

服務:

@Injectable() 
export class MyService { 
    customerUpdate$: Observable<any>; 

    private customerUpdateSubject = new Subject<any>(); 

    constructor() { 
     this.customerUpdate$ = this.customerUpdateSubject.asObservable(); 
    } 

    updatedCustomer(dataAsParams) { 
     this.customerUpdateSubject.next(dataAsParams); 
    } 
} 

記住添加MyService給供應商。

如果您更新您的客戶端(如果是這種情況),你做這樣的事情:

組件(即觸發一個):

constructor(private myService: MyService) { 
     // I'll put this here, it could go anywhere in the component actually 
     // We make things happen, Client has been updated 
     // We store client's data in an object 
     this.updatedClient = this.myObjectWithUpdatedClientData; // Obj or whatever you want to pass as a parameter 
     this.myService.updatedCustomer(this.updatedClient); 
    } 

分量(一說訂閱):

this.myService.customerUpdate$.subscribe((updatedClientData) => { 
      // Wow! I received the updated client's data 
      // Do stuff with this data! 
     } 
    ); 

從我的理解,你想傳遞數據從1個組件到另一個組件。你得到你的客戶數據並通過你的應用程序發送給另一個組件,對吧?這就是我發佈這個解決方案的原因。

如果你有興趣在其他類型的訂閱,閱讀:

Angular 2 special Observables (Subject/Behaviour subject/ReplaySubject)