1

API CALL

tmp:any;
getData(){
      this.api.getFiles().subscribe((res)=>{
        console.log(res);
        this.tmp=res;
      })
   }

Here I am able to get data from Api when i use console to check response then it is showing correct result but when i assign it a variable and accessing variable showing undefined. this is data

{
    "files":[
    {
        "id":23,
        "name": "file3",
        "path":"",
        "status": "processed",
        "annotation": "manual",
        "uploadedTime": "12-10-2012 10:24:14",
        "size": 10.23,
        "children":[]
   }
  ]
}
Vikash Mishra
  • 319
  • 3
  • 11
  • I have a feeling that the issue might be this: https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular But just guessing as you need to provide a [mcve] – AT82 Dec 03 '21 at 09:19
  • Please let us know the properties of that value, and which property you are trying to access – Deepak Dec 03 '21 at 09:20
  • Maybe you need trigger `detectChanges()`? – Anton Marinenko Dec 03 '21 at 09:26
  • Thanks for adding data. Also please show the line you use to access this – Deepak Dec 03 '21 at 09:28
  • It has to do with where you are accessing the variable. The thing inside the subscribe will run when there is a result from the API, while the things just outside of the subscribe will run just after the call to the API has been made. – ShamPooSham Dec 03 '21 at 09:28
  • @ShamPooSham inside subscribe i am able to get data, what i need to assign the result to variable so that anywhere in code i will able to use that response but it is only accessible in subscribe. let me how can i use that data outside – Vikash Mishra Dec 03 '21 at 09:40
  • @VikashMishra Yes, it's normal. You should probably add the other code inside the subscribe callback. Could you please share the code that shows where you access it and maybe what you do with it? – ShamPooSham Dec 03 '21 at 09:55

1 Answers1

1

I was trying access variable in ngOnIt till that variable is not initialized.So getting undefined. refer here

Vikash Mishra
  • 319
  • 3
  • 11