0

I have this service that fetches the data from my mongo collection through the node server

this._api.getCompanyData().subscribe(data =>  this.companydata = data)
localStorage.setItem("officeaddress",this.companydata.regofficeAddress) //this shows error that cant read regofficeAddress of undefined

this works fine in the template file when i use {{ companydata.regofficeAddress }}

but i want to fetch the particular value (officeaddress) in the controller itself.

Aayush Gupta
  • 504
  • 1
  • 5
  • 28
  • Then just use `_api.getCompanyData()`? – Andrey Popov Jun 04 '21 at 17:22
  • Why delete last question and post it again, your answer is in the duplicate, please read it and understand, as this is something you will deal with all the time. Welcome to the asynchronous world! :) – AT82 Jun 04 '21 at 17:32
  • the question which is being referred to me as a duplicate is not at all related to my query thats why i posted again – Aayush Gupta Jun 04 '21 at 17:42
  • @AndreyPopov can u pls post an answer with some code. – Aayush Gupta Jun 04 '21 at 17:42
  • 1
    @AayushGupta, it is spot on your question. This is **asynchronous** you need to handle everything inside **subscribe**. Please carefully read the question and accepted answer in the duplicate. The problem is **identical** and you will need to understand this for the future, as you will deal with this on every http-request when using observables. – AT82 Jun 04 '21 at 17:52
  • 1
    I must fully agree with @AJT82. Maybe I didn't get the question properly the first time, but if you'd like to get your data in the controller itself, you need to call your method **and** handle the response in the handler itself (the function inside `subscribe`. Read the other question/answer carefully and you'll see how this works. Good luck! – Andrey Popov Jun 07 '21 at 14:42

1 Answers1

0

You could do this to pick the regofficeAddress directly.

this._api.getCompanyData()
        .pipe(pluck('regofficeAddress'))
        .subscribe(data =>  this.companydata = data)
Adithya Sreyaj
  • 1,710
  • 10
  • 22