使用combineLatest运算符前,请确保两个主题都已完成初始化。否则,当任何一个主题发生更改时,combineLatest函数将不会发出任何值。
示例代码:
import { combineLatest } from 'rxjs';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
subject1 = new BehaviorSubject(null);
subject2 = new BehaviorSubject(null);
ngOnInit(): void {
this.subject1.next('hello');
this.subject2.next('world');
combineLatest(this.subject1, this.subject2).subscribe(([s1, s2]) => {
console.log(s1 + ' ' + s2); // output: "hello world"
});
}
}
在上面的示例中,combineLatest函数等待subject1和subject2都有初值后。当它们中任何一个主题更改时,该函数仅发出新的combined输出值。