嘗試通過這種方式構建服務:
服務:
@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)
你嘗試一個空的對象?新的BehaviorSubject
即時發生錯誤提供的參數不匹配調用目標的任何簽名。 – None
有一個解決方案。如果您不需要初始值,請勿使用BehaviorSubject。 – estus