0

I am writing a log service, in the log service have several log info. if I fetch IP address, it will fetch IP address after some delay, IP address as undefined in the error object.because

 logError(response: any): any {

      let errors:any;
      console.log(response, "log service error");
      this.getIP();

      error = {
        ExceptionMessage: response.message,
        ipaddress: this.getIP(),//  is undefined

        htmlDOM: document.getElementsByTagName("body")
        screenShot:another service call,
      }

      console.log(error, 'logged');
      return error;
 }

 getIP() {
   this.getIPAddress().subscribe((res: any) => {
      //getting ipaddress
      return res.ip;
   });
 }

 getIPAddress() {
   return this.httpClient.get("http://api.ipify.org/?format=json");
 }

 getScreen() {}

O.p: currently it works by using this set timeout solution.Better solution appreciated.

Tried with async and await but it did not work,

 logError(response: any): any {

       setTimeout(()=>{

          let errors:any;
          console.log(response, "log service error");
          this.getIP();
          error = {
            ExceptionMessage: response.message,
            ipaddress: this.getIP(),//  is undefined

            htmlDOM: document.getElementsByTagName("body")
            screenShot:another service call,
          }

          console.log(error, 'logged');
           return error;
         },7000);

         return error;
}
Shijil Narayanan
  • 1,011
  • 8
  • 21
Mohamed Sahir
  • 2,482
  • 8
  • 40
  • 71
  • Try `getIP() { this.getIPAddress().subscribe(res => { this.error.ipaddress = res.ip; }); }`. – ConnorsFan May 26 '20 at 15:11
  • @connorsFan that I am not defined globally let error is locally declared in that method. – Mohamed Sahir May 26 '20 at 15:13
  • You could pass the `error` object in `getIP(error)`, and set `error.ipaddress` inside of the subscribe callback. – ConnorsFan May 26 '20 at 15:17
  • 1
    According to the updated question, I would suggest to get the IP address when the service is initialized, so that you don't have to query it when it is time to log the error. Otherwise, you will have to log inside of the subscribe callback (at least the first time you query the IP address, after that you could reuse it). – ConnorsFan May 26 '20 at 15:34

0 Answers0