So I am new to Angular TypeScript and I have a problem.
So I have two files here, one is my component file with the function I use on Screen, and second one is HTTP service file where I make calls to a server.
Current my code structure is,
UserProfileComponent.ts
import { Component, OnInit } from '@angular/core';
import { UserService } from 'src/app/services/user.service';
@Component({
selector: 'app-userprofile',
templateUrl: './userprofile.component.html',
styleUrls: ['./userprofile.component.scss']
})
export class UserprofileComponent implements OnInit {
dataObj: any;
constructor(private userService: UserService) {
this.dataObj = this.userService.testCall();
console.log('dataObj-> ' + JSON.stringify(this.dataObj));
}
ngOnInit() {
}
}
and user.service.ts where I have this call
testCall(): any{
let responseObj: any;
this.http.get(`${this.baseUrl}/users`).subscribe((data) => {
console.log('responseObj-> '+JSON.stringify(data));
responseObj = data;
});
return responseObj;
}
So this issue for me is to handle the async call, the console.log('dataObj-> ' + JSON.stringify(this.dataObj))
does not wait for the service call to end and thus prints undefined
.
I know this is the working but how do I handle this programatically?
I want the response data before I proceed to the next line.
Angular CLI: 8.3.25, Node: 12.16.1, OS: win32 x64, Angular: 8.2.14
The problem is that you do subscribe
in your service, but instead you should do it in your component and return Observable
from service.
So the final code should look like:
testCall(): Observable<UserType[]> {
//I suppose you return Array of Users
return this.http.get(`${this.baseUrl}/users`);
}
and component
export class UserprofileComponent implements OnInit {
dataObj: UserType[];
constructor(private userService: UserService) {
}
ngOnInit() {
this.userService.testCall()
.subscribe((response: UserType[]) => {
dataObj = response;
console.log('dataObj-> ' + JSON.stringify(this.dataObj));
});
}
}