我将创建一个单独的服务来发出您的 http 请求:
@Injectable()
export class RandomService {
constructor(http: HttpClient) { }
getRandom() {
return this.http.get('http://mywebserver.com/apps/random.php');
}
}
现在你可以简单地打电话randomService.getRandom()
代替setInterval
,但你也可以使用可观察的操作(有一个Observable.interval
例如)为您处理这个问题ionViewDidLoad
:
async function ionViewDidLoad() {
let loader = this.LoadingController.create({
content: 'Please Wait',
});
await loader.present();
// x number of seconds
this.interval$ = interval(x).pipe(
// make first request right away; otherwise we have to wait x seconds before first one
startWith(),
// cancel previous request if it had not finished yet
switchMap(() =>
// catch the error inside to allow for a retry each time
// you could also use `.catch` on the entire observable stream which will
// cancel it if there's an error.
this.randomService.getRandom().catch(err => {
console.error(err);
this.alertCtrl
.create({
title: 'Error!',
subTitle: 'Please check your Internet Connectivity',
buttons: ['OK'],
})
.present();
}),
),
);
this.interval$.subscribe(data => this.fact = data);
// Separate observable to dismiss loader on first emission
this.interval$.pipe(first()).subscribe(() => loader.dismiss());
}
ionViewWillUnload() {
this.interval$.unsubscribe();
}
注意:这是假设使用 RxJS 5.5 和 AngularHttpClient
。您可能没有这些,但您仍然可以做一些非常类似的事情。如果您不使用可出租运算符,您将无法使用管道HttpClient
你还要做.map(data => data.json())
我会在服务中这样做。
最后,如果可以的话,请避免存储和手动取消订阅,如下所示this.interval$
。相反,你可能会做类似的事情this.fact$ = interval(x)...
然后在你的模板中你可以做*ngFor="let fact of (fact$ | async)"
并且您不必手动取消订阅。