【发布时间】:2021-06-08 09:43:27
【问题描述】:
我正在尝试使用 setInterval 从服务中调用数据。 当我从 ngOnInit 调用它时,它工作正常。 但是当我通过任何其他函数调用它时,它会给我以下错误: "ERROR TypeError: Cannot read property 'get' of undefined"
'''
public apiCall(mints:number){
console.log("from setinterval");
// console.log("api called");
// this.refInrvl=setInterval(()=>{
this.http.get('https://jsonplaceholder.typicode.com/posts').subscribe(resp=>{
this.storeD=resp;
});
// },3000)
}
public refreshSearch(){
console.log(this.refMints);
this.setIntvl();
}
public refreshList(refMints:number){
//this.refMints=refMints;
console.log("Sel Number",this.refMints);
this.setIntvl();
}
public setIntvl(){
this.refInrvl=setInterval(this.apiCall,(this.refMints*300*60),this.refMints);
}
'''
【问题讨论】:
-
你是 http 一个 HttpClient 吗?
constructor(private http:HttpClient){},应该可以。顺便说一句,我更喜欢使用timerrxjs 运算符而不是 setInterval -
很可能是“这个”。未指向在构造函数中注入的正确对象 httpClient。
-
当 this.apiCall 传递给 setInterval 时,
this的上下文丢失。使用this.apiCall.bind(this)。 -
@Eliseo 我已经在构造函数 http 中添加了您可以在下面的代码中看到。公共参考:数量=1;构造函数(私有 http:HttpClient){ } ngOnInit(): void { this.apiCall(this.refMints);我想同时使用 interval 和 clearinterval 因此使用 setinterval。
-
@enno.void,感谢您的解决方案,它在我身边有效。非常感谢...!!!
标签: angular typescript api