C
C
Chvalov2019-01-21 22:29:49
Angular
Chvalov, 2019-01-21 22:29:49

How to wait for response from Angular service?

There is an ApiService through which requests are made to the back

api.service.ts
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));
    }
}
Project Model:
project.model.ts
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[];
}
Service that processes requests for projects:
project.service.ts
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);
    }
}
And the component in which I should receive data from the service:
project-list.component.ts
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);
    }

And here's the problem, in the Developer Tools, I see that the request to the back is completed, but the variable test -> undefined
Created a method that is called when the button is clicked
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 after
this.projectService.getAll().subscribe(data => this.test = data);
without waiting for an answer.
How to fix ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
JokerS_Smile, 2019-01-21
@Chvalov

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

V
Vladimir, 2019-01-21
@Casufi

https://www.udemy.com/the-complete-guide-to-angular-2/
Here they tell the basics and work with RxJS and even NgRx in the end. Enough to start, and then it's up to you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question