在我的component.ts中,我正在从服务类中调用一个函数,该函数从后端rest api中检索数据。记录结果时,我成功检索了数据,但尝试在组件中订阅数据时没有任何反应
vehicles: VehicleDto[] = [];
constructor(private myService: MyService) {
console.log(this.myService.getVehicles());
console.log("Before Service call");
this.myService.getVehicles().subscribe((result: any[]) => {
console.log("service called");
this.vehicles = result;
console.log(this.vehicles); //this is console for vehicles
});
console.log("after service call");
}
在我的服务班级:
getVehicles() : Observable<VehicleDto[]> {
let resultSubject: AsyncSubject<VehicleDto[]> = new AsyncSubject();
let httpOptions = this.kecloakService.buildHeaderWithToken();
this.configurationService.loadNetworkConfiguration(false).subscribe((config: NetworkConfiguration) => {
if (config) {
this.http.get(config.getHostUrl + this.url + "getVehicles", httpOptions)
.subscribe((entities: VehicleDto[]) => {
let results: VehicleDto[] = [];
for(let entity of entities) {
results.push(entity);
}
resultSubject.next(results);
resultSubject.complete;
});
}
});
return resultSubject;
}
如您所见,我确实将阵列取回来,但是在订阅中,结果永远不会被记录或分配给载具。
答案 0 :(得分:1)
这是由于异步性质。请告知您有关回调的信息。如果您在理解回调方面有困难,请随时使用async-await。 摆脱嵌套订阅!
// Variant A+B
vehicles: VehicleDto[];
// Veriant C
vehicles$: Observable<VehicleDto[]>;
constructor(private myService: MyService) {
// Variant A: async-await
this.vehicles = await this.myService.getVehiclesPromised();
// Variant B: callback (least recommended, do not forget to unsubscribe!)
// this.myService.getVehicles().subscribe((result: VehicleDto[]) => {
// this.vehicles = result;
// });
// Variant C: Observable (use async pipe in template to access data)
//this.vehicles$ = this.myService.getVehicles();
}
async getVehiclesPromised(): Promise<VehicleDto[]> {
const httpOptions = this.kecloakService.buildHeaderWithToken();
const config: NetworkConfiguration = await this.configurationService.loadNetworkConfigurationPromised(false);
return config ? await this.http.get(config.getHostUrl + this.url + "getVehicles", httpOptions).toPromise() : [];
}
答案 1 :(得分:0)
您可以创建一个Observable并可以正常工作:
getVehicles(): Observable<VehicleDto[]> {
let httpOptions = this.kecloakService.buildHeaderWithToken();
return new Observable((obs => {
this.configurationService.loadNetworkConfiguration(false).subscribe((config: NetworkConfiguration) => {
if (config) {
this.http.get(config.getHostUrl + this.url + "getVehicles", httpOptions)
.subscribe(
(entities: VehicleDto[]) => {
let results: VehicleDto[] = [];
for (let entity of entities) {
results.push(entity);
}
obs.next(results);
obs.complete();
}
);
}
});
}));
}
答案 2 :(得分:0)
您可以将最后一行更改为:
return resultSubject.asObservable();
,服务将返回类型为Observable<VehicleDto[]>
的对象,您当前正在返回类型为AsyncSubject
的对象;