Answer the question
In order to leave comments, you need to log in
How to wait for response from Angular service?
There is an ApiService through which requests are made to the back
const BASE_URL = 'http://127.0.0.1:8080/api/';
const VERSION = 'v1';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
};
@Injectable()
export class ApiService {
readonly rootUrl = BASE_URL + VERSION + '/';
constructor(private httpClient: HttpClient) { }
// GET
public get(path: string): Observable<any> {
return this.httpClient
.get(this.rootUrl + path, httpOptions)
.pipe(catchError(this.formatErrors));
}
}
import {Request} from "./request.model";
export interface PageProject {
content: Project[];
totalPages: number;
totalElements: number;
last: boolean;
size: number;
first: boolean;
sort: string;
numberOfElements: number;
}
export interface Project {
id: number;
name: string;
description: string;
created: string;
updated: string;
requests: Request[];
}
const routes = {
projects: 'projects',
project: (id: number) => `projects/${id}`
};
@Injectable()
export class ProjectService {
constructor(private apiService: ApiService) { }
public getAll(): Observable<PageProject> {
return this.apiService.get(routes.projects);
}
}
export class ProjectListComponent implements OnInit {
constructor(private projectService: ProjectService) { }
test: PageProject;
ngOnInit(): void {
this.projectService.getAll().subscribe(data => this.test = data);
console.log(this.test);
}
getTestLog(): void {
console.log(this.test);
}
when this method is called, there is already data in the variable, as it turned out, it console.log()
is executed immediately afterthis.projectService.getAll().subscribe(data => this.test = data);
without waiting for an answer. Answer the question
In order to leave comments, you need to log in
The lambda from subscribe will be executed after the response arrives, you can put console.log into this lambda to see what came in the response
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question