我是TypeScript和Angular8的新手
我有以下代码是要从Web服务获取数据的。当前,它返回null
,但是如果我在console.log(this.service_type)
块结束之前的行中添加if (user.status == 200) {
,我将得到正确的数据,如何返回正确的数据
我在做什么或做错了什么?
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}
}
}```
答案 0 :(得分:1)
您遇到了一个障碍,即大多数开发人员在首次被引入异步编程和反应式编程的概念时都会陷入困境。您有一个方法getRewardServices
,它返回一些Observable
,您的服务已订阅该方法,并为该可观察到的每个元素执行回调(您可以阅读更多here)。关键问题在这一行:
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;
});
}
答案 1 :(得分:1)
调用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>