Having trouble retrieving data from a request? I've encountered an issue where the data retrieved inside .subscribe
in an observable function is returning as undefined
when trying to access it outside the function. It's quite frustrating!
Here is a snippet of the code in Component.ts:
import { ProjectService } from '../services/project.service';
@Component({
selector: 'app-project-loader',
templateUrl: './project-loader.component.html',
styleUrls: ['./project-loader.component.css']
})
export class ProjectLoaderComponent implements OnInit {
projects:any;
constructor(private projectService: ProjectService) { }
ngOnInit(): void {
this.getProjects();
}
getProjects(){
this.projectService.getProjects().subscribe(data=>{
this.projects= data;
})
}
}
Take a look at the Component.html file:
{{projects[0].id}}
Currently, the HTML is just being used for testing purposes with only one line. Just so you know, the data returned in the observable function is a JSON array.
Here is an example of the array:
{
"id": "REDACTED",
"projectName": "REDACTED",
"projectId": "REDACTED"
},
{
"id": "REDACTED",
"projectName": "REDACTED",
"projectId": "REDACTED"
}
]
(The redacted strings are from a private database :P)