I am making calls to my back-end service using an independent TypeScript class. I am able to console.log
the captured data when instantiating the instance of my shared class. However, I am having trouble accessing the local properties and methods of that class inside my angular component.
Here is my component:
import { Component, OnInit } from '@angular/core';
import { ProjectService } from '../shared/projectService';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-about',
templateUrl: './about.component.html',
styleUrls: ['./about.component.css']
})
export class AboutComponent implements OnInit {
projects: any;
windowWidth: number;
service: ProjectService;
constructor(private httpClient: HttpClient) {
this.service = new ProjectService(this.httpClient);
// returns as undefined
console.log(this.service.getAllProjects());
}
ngOnInit() {
this.windowWidth = window.innerWidth;
}
}
Here is my shared class module:
import { HttpClient } from '@angular/common/http';
interface Project {
demoURL: string,
githubURL: string,
imgFileName: string,
name: string,
stack: Array<string>
}
export class ProjectService {
private configURL = `https://someURL.herokuapp.com/getAllProjects`;
projects: any;
constructor(private httpClient: HttpClient) {
this.httpClient.get(this.configURL).subscribe(resp => {
this.projects = resp;
});
}
getAllProjects() {
return this.projects;
}
}
As you can see,
I want to populate my local variable projects
inside my ng component using this.service.getAllProjects()
. When I try to log the response from my shared class ProjectService
the function response is undefined
.
When I console.log
inside ProjectService
constructor after I initialize the class using new
I can see that my class was able to capture the response.
Why is it doing this? Also, how do I fix it?
Thanks guys.
Okay, so what worked for me was using EventEmitter to emit the projects when the http request completed, as mentioned by
user1986938
.This is what I did:
HttpService:
Component: