您好我正在测试如何使用计时器使用订阅在一个时间范围内运行一个函数。我遇到的问题是,一旦我取消订阅并更改组件,该方法就会被调用。我想知道如何阻止它。这是我的代码:
`
import { Component, OnInit, AfterViewChecked, AfterContentInit, AfterViewInit, OnDestroy } from '@angular/core';
import $ from 'jquery';
import { Headers, Http } from "@angular/http";
import "rxjs/Rx";
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
// Variables that load the respectively JavasScript methods in the JavaScript file SharedContents/plugins/flot-charts/jquery.flot.js
declare var initRealTimeChart: any;
declare var initSparkline: any;
declare var initDonutChart: any;
@Component({
selector: 'home',
template: require('./home.component.html')
})
export class HomeComponent implements OnInit, AfterViewChecked, AfterContentInit, AfterViewInit, OnDestroy {
_message: string;
foo;
private subscriptions: Array<Subscription> = [];
//called first time before the ngOnInit()
constructor(private http: Http) {}
//called after the constructor and called after the first ngOnChanges()
ngOnInit(): void {
this._message = "adsad";
console.log(this._message);
//setInterval(() => this.getLog("Home/GetTest"), 500);
this.subscriptions.push(this.getLog("Home/GetTest").subscribe(
response => {
console.log('Success ' + response);
},
err => {
console.log('Error' + err)
},
() => {
console.log('Complete')
}
));
}
ngAfterContentInit(): void {
}
ngAfterViewChecked(): void {
}
ngAfterViewInit(): void {
initRealTimeChart();
initSparkline();
initDonutChart();
}
ngOnDestroy(): void {
console.log("ngOnDestroy!");
this.subscriptions.forEach((subscription: Subscription) => {
console.log("Destroying Subscription :", subscription);
subscription.unsubscribe();
});
}
public TestStuff() {
console.log("Run TestTSuff");
return this.http.get("Home/GetTest")
.toPromise()
.then(response => {
response.json().data;
console.log('GOT IT!');
console.log(response);
})
.catch((ex) => {
console.log(ex);
console.log(ex._body);
});
}
getLog(url: string): Observable<string> {
return Observable
.timer(0, 12000)
.concatMap(() => this.get(url))
///.retryWhen(error => error.delay(12000))
.map((data: any) => {
console.log('Request Success!')
data.json();
return data.json();
})
.catch(e => {
//console.warn(e.toString());
return Observable.from("ERROR" + e);
});
}
get(url) {
return this.http.get(url);
}
}
`
答案 0 :(得分:0)
我设法解决了这个问题。
我只需要清除浏览缓存。
感谢所有的帮助。