在使用switchMap时,使用pipe操作符结合startWith运算符将初始值传入pipe中,这样一来switchMap就会在发出最新值前首先发出初始值。 代码示例:
import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import { switchMap, startWith } from 'rxjs/operators'; import { Store } from '@ngrx/store'; import { AppState } from '../app.state';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
myValue$: Observable
constructor(private store: Store
ngOnInit() { this.myValue$ = this.store.select('myValue').pipe( startWith('initialValue'), switchMap(newVal => { // do something with newVal return newVal; }) ); } }