我是 RxJS 中的 BehaviourSubject 新手,我正在尝试使用它来跨组件共享数据。我不确定具体如何使用它。我的组件中的代码是
export class CarsListComponent implements OnInit {
cars: Cars[] = [];
constructor(private carsListService: CarsListService) { }
ngOnInit() {
this.carsListService.getCars()
.subscribe(response => {
this.cars= response;
}, error => {
console.log(error);
});
}
}
我的服务中的代码是
export class CarsService {
constructor(private http: HttpClient) {}
getCars(): Observable<Car[]> {
return this.http.get<Car[]>(url,headers)
.pipe(
map(response => response)
);
}
}
我不知道如何使用BehaviourSubject以及如何实现它。请帮我解决这个问题。
最佳答案
从这个问题来看,我认为你正在尝试使用相同的 this.cars
跨多个组件。如果您想分享它,请使用 BehaviorSubject
是一种方法,因为即使已经订阅了它,它也会存储该值。
让我们创建一个共享服务,该服务将被注入(inject)到多个组件中,比如 app-shared.service.ts
app-shared.service.ts
:
import { Injectable } from '@angular/core';
import { BehaviorSubject , Observable} from 'rxjs';
@Injectable()
export class AppSharedService {
carsListSubjectt : BehaviorSubject<Cars[]> = new BehaviorSubject<Cars[]>([]);
constructor() { }
updateCarsList(cars : Cars[]) : void{
this.carsListSubjectt.next(cars);
}
getCarsList() : Observable<Cars[]>{
return this.carsListSubjectt.asObservable();
}
}
export interface Cars{
carType : string ;
manufacturedDate : Date;
condition : string;
}
注意: Cars
接口(interface)只是我的定义。使用您的定义。
现在你只需 inject
app-shared.service
在您所需的组件中。
要更新数据,请使用您的代码:
export class CarsListComponent implements OnInit {
cars: Cars[] = [];
constructor(private carsListService: CarsListService, private _appSharedService : AppSharedService) { }
ngOnInit() {
this.carsListService.getCars()
.subscribe(response => {
this.cars= response;
this._appSharedService.updateCarsList(response);
}, error => {
console.log(error);
});
}
}
您只需订阅 getCarsList()
app-shared.service
中定义因为它将返回 Observable<Cars[]>
.
请告诉我这是否有帮助:)
关于angular - 在服务中使用映射运算符并在组件中订阅时的 RxJS BehaviouSubject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58967489/