以下是示例代码:
共享服务代码:
import { HttpClient } from '@angular/common/http'; import { BehaviorSubject } from 'rxjs'; import { tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class SharedService {
private dataSubject: BehaviorSubject
constructor(private http: HttpClient) { }
getData() {
this.http.get
组件代码:
import { Component, OnInit } from '@angular/core'; import { SharedService } from './shared.service'; import { switchMap } from 'rxjs/operators';
@Component({ templateUrl: './my-component.component.html' }) export class MyComponent implements OnInit { data$ = this.sharedService.data$;
constructor(private sharedService: SharedService) { }
ngOnInit() { this.sharedService.getData(); this.data$ = this.data$.pipe( switchMap(() => this.sharedService.data$) ); } }
在组件中,我们首先订阅了“BehaviorSubject”对象,然后使用“switchMap”运算符切换到共享服务中获取最新数据的可观察对象。当共享服务获取新数据时,它将使用“tap”运算符更新“BehaviorSubject”对象。这确保了我们获得最新的数据。