【发布时间】:2017-07-28 21:51:10
【问题描述】:
问题
我有一个看起来像这样的服务:
DogService {
public getSelectedDog(): Observable<Uuid> {...}
public getDog(dogUuid: Uuid): Observable<Dog> {...}
}
我想创建一个始终包含我选择的狗的 Observable,即Observable<Dog>。
到目前为止我所尝试的
目前我正在做的是:
let selectedDog: Observable<Dog> = dogService.getSelectedDog().flatMap( selectedDog => {
return dogService.getDog( selectedDog );
});
然后您可以像这样订阅所选狗的更改:
selectedDog.subscribe( dog => console.log( 'dog: ", dog.name, dog.mood );
不幸的是,这似乎不像我预期的那样工作。 selectedDog 仅可观察 当 selectedDog 发生变化时触发,而不是当狗本身发生变化时触发。
例如,假设我们执行以下操作:
const dog1: Dog = new Dog( '1', // uuid
'Shadow', // name
'happy' // mood
);
const dog2: Dog = new Dog( '2', // uuid
'Barky', // name
'Angry' // mood
);
// Fires the getDog observable
dogService.addDog( dog1 );
// Fires the getDog observable
dogService.addDog( dog2 );
// Fires the getSelectedDogObservable
dogService.selectDog( dog1.uuid )
// --- Now in console.log we will see: 'dog: Shadow happy'
不幸的是,如果我更新狗,控制台不会登录到:
const updatedDog1: Dog = new Dog( '1', // uuid
'Shadow', // name
'SAD' // mood
);
// Fires the getDog observable
dogService.updateDog( updatedDog1 );
// --- the console.log doesn't get invoked. Crap.
问题:我如何创建Observable<Dog>,它会在选择或选定的狗发生变化时触发?
【问题讨论】:
-
为了解决这个问题,您需要包含服务实现,因为这就是必须进行更改的地方。
-
@cartant - 我不认为这是真的......
-
@cartant 是正确的,我认为您可能会在您的服务中使用一个主题来更新其余的 observables
标签: typescript observable rxjs5