我正在使用Angular 4应用程序,在此我需要从我的服务文件中调用API。
这里我每隔15分钟在服务文件中调用一次方法。但它显示如下错误
但是如果我在没有传递参数的情况下调用API它工作正常,当我从服务中调用一个方法将参数传递给API时,它就不会被触发。
服务方法
update_User_Session() {
this.publicIp.v4().then(ip => {
this.END_USER_SESSION(ip)
})
this.publicIp.v4().then(ip => {
this.INSERT_USER_SESSION(ip)
})
}
INSERT_USER_SESSION(address: string) {
this.http.get(`http://localhost:xyz/api/data/INSERT_USER_SESSION/?IP_Address=${address}&Time=${this.date_and_time}&state=${this.session_Begin_Status}`)
}
END_USER_SESSION(address: string) {
this.http.get(`http://localhost:xyz/api/data/INSERT_END_USER_SESSION/?Ip_Address=${address}&Time=${this.date_and_time}&state=${this.session_End_Status}`)
}
来自我的组件
constructor(private CartdataService: CartdataService, private http: HttpClient) {
this.call = Observable.interval(90000)
.switchMap(() => this.CartdataService.update_User_Session())
.subscribe((data) => {
console.log(data);
});
}
此处此行.switchMap(() => this.CartdataService.update_User_Session())
变为红色,并在图片
任何人都可以告诉我,我在哪里犯了错误。
答案 0 :(得分:0)
//use retryWhen from rxjs like below
//first import retryWhen and delay operators in your service file.
//use before subscribe like below example as i given.
import 'rxjs/add/operator/retrywhen';
import 'rxjs/add/operator/delay';
ngOnInit() {
let empCode: string = this._activatedRoute.snapshot.params['code'];
this._employeeService.getEmployeeByCode(empCode)
// Retry with a delay of 1000 milliseconds (i.e 1 second)
.retryWhen((err) => err.delay(1000))
.subscribe((employeeData) => {
if (employeeData == null) {
this.statusMessage =
'Employee with the specified Employee Code does not exist';
}
else {
this.employee = employeeData;
}
},
(error) => {
this.statusMessage =
'Problem with the service. Please try again after sometime';
console.error(error);
});
}
答案 1 :(得分:0)
Use observable.timer for your purpose in angular way.
private timer;
constructor(private CartdataService: CartdataService, private http: HttpClient) {
}
ngOnInit() {
this.timer = Observable.timer(9000);
this.timer.subscribe((t) => this.onTimeOut());
}
onTimeOut() {
this.CartdataService.update_User_Session().then(
success => {
if(success ['ok'] == 0){
console.log('test');
}
},
error => { console.log(error); });
}
ngOnDestroy(){
console.log("Destroy timer");
}
}