I am currently using Angular 9 and I am having some issues with accessing a global variable. I can access the listOfProjects variable when I pass an ES6 callback function to map
but when I use a normal function I get an error saying that Cannot read property 'push' of undefined
. I think that the variable has gone out of scope. I am little bit lost regarding how to fix this. Also if you see any bad practices in my code please feel free to point them out as well as I am fairly new to angular.
The code with the normal function:
export class DataService {
listOfProjects: Project[] = [];
API_URL: string = "API_URL";
homePageHeading: string;
constructor(private httpClient: HttpClient) { }
getProjects() {
this.listOfProjects.length = 0;
this.httpClient.get<any[]>("API_URL").pipe(
map(function mapData(res) {
this.homePageHeading = res[0].heading
res[0].projects.map( (project) =>
this.listOfProjects.push(
{
"company": project.company,
"description": project.description,
"imageUrl": this.API_URL + project.image[0].url,
"Link": project.Link
})
)
})
).subscribe(res => {
console.log(this.listOfProjects);
});
}
}
The code with the normal function:
export class DataService {
listOfProjects: Project[] = [];
API_URL: string = "API_URL";
homePageHeading: string;
constructor(private httpClient: HttpClient) { }
getProjects() {
this.listOfProjects.length = 0;
this.httpClient.get<any[]>("API_URL").pipe(
map((res) => {
this.homePageHeading = res[0].heading
res[0].projects.map( (project) =>
this.listOfProjects.push(
{
"company": project.company,
"description": project.description,
"imageUrl": this.API_URL + project.image[0].url,
"Link": project.Link
})
)
})
).subscribe(res => {
console.log(this.listOfProjects);
});
}
}