I've been working on an Angular2 and Typescript application where I'm utilizing Angular2's HTTP methods to retrieve data from a database within a service. The service is triggered inside a component's onInit() function and I'm able to successfully load the data. However, I'm facing an issue where I want to also use this loaded data within the onInit() function itself. Whenever I attempt to do this, I encounter an error similar to the one below:
Error: Uncaught (in promise): TypeError: Cannot read property 'user_id' of undefined
TypeError: Cannot read property 'user_id' of undefined
Below is a snippet of the component calling the service:
export class ProfileComponent implements OnInit {
public profile: StaffProfile[];
constructor(private userService: UserService) {}
ngOnInit() {
this.userService.fetchProfile();
this.profile = this.userService.getProfile();
// I want to perform operations once the data is loaded
console.log(this.profile[0].user_id);
}
}
Below is a snippet of the service:
@Injectable()
export class WorkforceUserService implements OnInit {
private Profile: Profile[];
constructor(private http: Http) {
this.Profile = [];
}
public getProfile(){
return this.Profile;
}
public fetchStaffProfile(){
return this.http.get('http://localhost:3000/api/staff/1')
.map((response: Response) => response.json())
.subscribe(
(data) => {
var user_id = data.user_id || null;
var loadedProfile = new Profile(user_id);
this.Profile.push(loadedProfile);
}
);
}
}
I'm looking for a way to trigger a function in my component once the data has been retrieved from the server or has been updated. Any insights on how I can achieve this would be greatly appreciated.
Thank you in advance.