当通过URL访问时得到空的BehaviorSubject,可能是以下几个原因:
import { BehaviorSubject } from 'rxjs'; export class MyService { private mySubject = new BehaviorSubject<any>(null); constructor() { // 确保在构造函数中初始化BehaviorSubject this.mySubject.next(someInitialValue); } getSubject() { return this.mySubject.asObservable(); } }
import { BehaviorSubject } from 'rxjs'; import { switchMap, startWith } from 'rxjs/operators'; import { of } from 'rxjs'; export class MyService { private mySubject = new BehaviorSubject<any>(null); constructor() { this.loadData(); } loadData() { this.mySubject.pipe( startWith(null), switchMap(() => this.fetchDataFromAPI()) ).subscribe(data => { this.mySubject.next(data); }); } fetchDataFromAPI() { // 模拟API调用 return of({ key: 'value' }).pipe(delay(1000)); } getSubject() { return this.my伪装Subject.asObservable(); } }
// 例如在NgRx中
import { Store } from '@ngrx/store';
import { updateData } from './actions';
export class MyComponent {
constructor(private store: Store) {
this.store.dispatch(updateData({ key: 'value' }));
}
}
领取专属 10元无门槛券
手把手带您无忧上云