首页 > 解决方案 > 从 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);
  }

'''

标签: angulartypescriptapi

解决方案


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))

推荐阅读