我是typeScript和Angular8的新手
我有以下代码,用于从web服务获取数据。当前,它返回null,但如果在console.log(this.service_type)块结束前将console.log(this.service_type)添加到行中,则如何返回正确的数据?
我没有做错什么或者做错什么?
import { User } from '../_models/user';
import { Router } from '@angular/router';
import { ApiService } from './api.service';
import { ServiceType, Donations, Betting, Topup } from '../_models/data';
@Injectable({
providedIn: 'root'
})
export class CheckService {
constructor(
private apiService: ApiService,
private router: Router
) {}
service_type: ServiceType = null;
donations: Donations = null;
betting: Betting = null;
services: Topup = null;
getReward() {
this.apiService.getRewardServices().subscribe(
user => {
if (user.status == 200) {
this.service_type = user.data.service_type;
this.donations = user.data.donations;
this.betting = user.data.betting;
this.services = user.data.services;
}
}
);
return {service_type: this.service_type, donations: this.donations, betting: this.betting, services: this.services}
}
}```发布于 2020-01-09 20:37:31
当第一次引入异步编程和反应性编程的概念时,大多数开发人员都会陷入困境。您有一些方法,getRewardServices,它返回服务订阅的一些Observable,并对这个可观察到的每个元素执行回调(您可以读取更多的这里)。关键的问题在于这一行:
return {service_type: this.service_type, donations: this.donations, betting: this.betting, services: this.services}它可以在可观察到的用户对象发出之前执行。解决这一问题的正确方法是将可观测到的映射到您想要返回的对象中,并返回可观察到的自身。外部服务/组件将负责展开可观察到的事件并处理异步事件。就像这样:
getReward(): Observable<any> {
return this.apiService.getRewardServices().pipe(
map(user => {
if (user.status == 200) {
this.service_type = user.data.service_type;
this.donations = user.data.donations;
this.betting = user.data.betting;
this.services = user.data.services;
return {service_type: this.service_type, donations: this.donations, betting: this.betting, services: this.services}
}
return some_other_error_value;
});
}发布于 2020-01-09 20:39:09
当调用getRewards()方法时,会发生以下情况:
您可以做些什么,而不是在方法中订阅数据,而是返回可观察的对象并与async管道一起使用它。
示例
服务:
export class CheckService {
constructor(
private apiService: ApiService,
private router: Router
) {}
rewardObject$: Observable<any>;
getReward() {
this.rewardObject = this.apiService.getRewardServices().pipe(map(user => {
if (user.status == 200) {
return {
service_type: user.data.service_type,
donations: user.data.donations,
betting: user.data.betting,
services: user.data.services,
};
return null;
}
}));
}
}模板:
<ng-container *ngIf="(rewardObject$ | async) as reward">
<span>{{reward.service_type}}</span>
</ng-container>https://stackoverflow.com/questions/59671333
复制相似问题