如何使用 Angular4 而不是设置间隔每 30 秒调用一个方法
how to call a method for every 30 seconds using Angular4 instead of Set interval
你好,我有一个方法可以从这里获取数据,我希望数据每 30 秒刷新一次,之前我使用了 setINTERVAL 方法,但是如果可以的话,我可以使用 Observable Interval 来代替,我该如何使用因为如果离开那个页面我想取消订阅那个方法
下面是我得到结果的代码
getOrderTrack(data){
this.serv.OrderTrackDetails(data).subscribe(res=>{
this.OrderTrack = res.CurrentOrderStatusResult;
console.log(this.OrderTrack);
},err=>{
console.log(err);
})
在 ngDestroy 中使用取消订阅,取消订阅 observable
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnDestroy {
private subscription: Subscription;
this.subscription = // Observable code
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
can i use Observable Interval if so how can i use this becoz if go out
of that page i want to unsubscribe from that method
您可以在任何地方退订。因此,如果您导航到另一个页面并且此组件将销毁,那么 ngOnDestroy 生命周期挂钩将被调用。
export class AppComponent {
name: any = 'Angular 5';
subscr: Subscription;
constructor(public http: HttpClient) {
}
getData() {
return this.http.get('https://jsonplaceholder.typicode.com/posts/1');
}
ngOnInit() {
this.subscr = Observable.interval(1000)
.flatMap(() => this.getData())
.subscribe(data => {
console.log('data', data);
this.name = data;
});
}
unsubscribe() {
this.subscr.unsubscribe();
}
ngOnDestroy() {
this.subscr.unsubscribe();
}
你好,我有一个方法可以从这里获取数据,我希望数据每 30 秒刷新一次,之前我使用了 setINTERVAL 方法,但是如果可以的话,我可以使用 Observable Interval 来代替,我该如何使用因为如果离开那个页面我想取消订阅那个方法
下面是我得到结果的代码
getOrderTrack(data){
this.serv.OrderTrackDetails(data).subscribe(res=>{
this.OrderTrack = res.CurrentOrderStatusResult;
console.log(this.OrderTrack);
},err=>{
console.log(err);
})
在 ngDestroy 中使用取消订阅,取消订阅 observable
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnDestroy {
private subscription: Subscription;
this.subscription = // Observable code
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
can i use Observable Interval if so how can i use this becoz if go out of that page i want to unsubscribe from that method
您可以在任何地方退订。因此,如果您导航到另一个页面并且此组件将销毁,那么 ngOnDestroy 生命周期挂钩将被调用。
export class AppComponent {
name: any = 'Angular 5';
subscr: Subscription;
constructor(public http: HttpClient) {
}
getData() {
return this.http.get('https://jsonplaceholder.typicode.com/posts/1');
}
ngOnInit() {
this.subscr = Observable.interval(1000)
.flatMap(() => this.getData())
.subscribe(data => {
console.log('data', data);
this.name = data;
});
}
unsubscribe() {
this.subscr.unsubscribe();
}
ngOnDestroy() {
this.subscr.unsubscribe();
}