【发布时间】:2016-08-06 01:35:33
【问题描述】:
Angular2 2.0.0-beta.15,Rxjs 5.0.0-beta.2
我有两个简单的 rxjs observables,一个共享,一个不共享(.share() 调用它)
我有一个 angular2 组件,它订阅两个 observables 并在其模板中显示值,它还通过异步管道订阅 observables。
我点击一个按钮在两个 observables 上设置 .next() 并带有一些垃圾。
模板更新并显示每个的最新值。 组件中的订阅函数不会为非共享的 observable 触发。为什么?
plunkr: https://plnkr.co/edit/IIWvnTT1zLit1eUNknkk?p=preview
@Component({
selector: 'my-app',
template: `
<div>
<div>obs1 value: {{ observable1 | async }}</div>
<div>obs2 value: {{ observable2 | async }}</div>
<button (click)="randomizeIt()">randomize it</button>
<br>
<h3>Question 1</h3>
Why is obs1's initial value (from startWith) not displayed?
<h3>Question 2</h3>
Why does our subscription to obs2 never fire on new values?<br>
check console.log to see what i mean.
</div>`,
})
export class App {
public observable1:Observable<string>;
public observer1:any;
public observable2:Observable<string>;
public observer2:any;
constructor() {
this.observable1 = Observable.create(observer => {
this.observer1 = observer;
}).startWith("initial obs 1 value").share();
this.observable1.subscribe((val) => {
console.log('YOU WILL SEE THIS:', val);
})
this.observable2 = Observable.create(observer => {
this.observer2 = observer;
}).startWith("initial obs 2 value"); // no share!
this.observable2.subscribe((val) => {
console.log('WHY DOES THIS NEVER FIRE ON NEW VALUES?:', val);
})
}
public randomizeIt() {
let r = Math.random();
console.log('set both obs to: ', r);
this.observer1.next(r);
this.observer2.next(r);
}
}
提前致谢!
【问题讨论】: