如何在Angular 4中调用具有特定时间间隔的API
我在Angular 4应用程序中工作,在这里我需要从我的服务文件调用API 这里我每隔15分钟调用一次服务文件中的方法 但是,如果我在不传递参数的情况下调用API,它工作得很好,当我从服务调用一个将参数传递给API的方法时,它不会被触发 服务方式如何在Angular 4中调用具有特定时间间隔的API,angular,Angular,我在Angular 4应用程序中工作,在这里我需要从我的服务文件调用API 这里我每隔15分钟调用一次服务文件中的方法 但是,如果我在不传递参数的情况下调用API,它工作得很好,当我从服务调用一个将参数传递给API的方法时,它不会被触发 服务方式 update_User_Session() { this.publicIp.v4().then(ip => { this.END_USER_SESSION(ip) }) this.publicIp.v4()
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\u User\u Session())
用红线表示,并显示上述错误,如图所示
谁能告诉我,我在哪里犯了错误。你的
更新用户会话
应该返回一个可观察的
,但是你返回空
你能用你的logics@mittalbhatt编辑我的代码吗
//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);
});
}
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");
}
}