divein
divein

Reputation: 57

Access specific object from array of objets via json file in angular 6

I have a JSON object in my assets folder I am reading as below

data.json

[ 
{
 "modName":"deployment",
 "year":"1992",
  "description":"basic deployment"
},

{
 "modName":"Integration",
  "year":"1995",
  "description":"popular integration"
}
]

In my dataService.ts file my reading JSON object

getData(){
 return this.http.get('assests/data.json');
}

getDataInfo{
 return this.getData().subscribe(data=>{
 if(data!==undefined)
  for(let i in data){
   if(data[i].modName=='deployment'){
     return data[i];
  }
  }
 })
}

I am accessing this object in my main component let data = this.dataService.getDataInfo()

this is giving me a subscriber though I want a specific data object.How can I retrieve it?

Upvotes: 0

Views: 135

Answers (1)

Žarko Selak
Žarko Selak

Reputation: 1131

getData goes in service, getDataInfo goes in component and then in component you can create variable myDataInfo and just on line where you return data do this

this.myDataInfo = data[i]

OR

same as above with service and component method, but you can store your data to some variable eg. this.myJsonData

and then you can do something like this

get myDataInfo() {
    return this.myJsonData.filter((item) => item.modName=='deployment')[0]
}

and the you just can use that object in your template easy.

Upvotes: 1

Related Questions