【问题标题】:get http data from function isntead of ngOnit in angular从函数获取http数据而不是角度的ngOninit
【发布时间】: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){},应该可以。顺便说一句,我更喜欢使用 timer rxjs 运算符而不是 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


【解决方案1】:
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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 2019-02-28
    相关资源
    最近更新 更多