angular - 从 ngOnit 的函数 istead 以角度获取 http 数据
问题描述
我正在尝试使用 setInterval 从服务中调用数据。当我从 ngOnInit 调用它时,它工作正常。但是当我通过任何其他函数调用它时,它会给我以下错误:“错误类型错误:无法读取未定义的属性'get'”
'''
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);
}
'''
解决方案
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class yourService {
baseUrl: string;
constructor(private httpClient: HttpClient) {
this.baseUrl = 'https://jsonplaceholder.typicode.com/posts';
}
public apiCall() Promise<any>{
this.http.get<any>(this.baseUrl).toPromise();
//.subscribe(resp=>{this.storeD=resp;});
}
}
要解决承诺,在任何组件中将服务注入构造函数,并解决承诺:
async getYorData() {
await this.serviceInComponent.apiCall().then(res => console.log(res)).catch(err => console.log(err))
}
出于运行时原因和定时函数的一些不可预测的行为,我建议在组件本身中使用 setTime 或 setInterval。
refreshResponse(time: number){
setTimeout(async () => {
await this.serviceInComponent.apiCall().then(res => console.log(res)).catch(err => console.log(err))
}, time);
}
console.log(refreshResponse(3000))
推荐阅读
- powershell - Powershell 强制将 ConvertFrom-Json 输出转换为字符串,然后可以将其用于所有字符串操作,包括。文件命名
- javascript - 我们如何在javascript中编写క్ష(泰卢固语)unicode(结合“ka”和“sha”字形)?
- javascript - React 有条件地在特定路由中渲染组件
- c++ - 如何使用 std::reduce 将 Windows 上的线程亲和性设置为最大值
- node.js - 使用 Google Sheets Node.js API 更新单元格颜色
- javascript - 如何通过新集合从对象中获取唯一数组?
- sql - 双管做字符串比较?
- javascript - 输入特定文本时,Javascript 输入会运行一个函数
- pytorch - Pytorch:如何创建一个随机整数张量,其中某个百分比具有某个值?例如,25% 为 1,其余为 0
- google-bigquery - BigQuery - 替换字符串中的空格