JavaScript - Clearing a variable after receiving data [duplicate]

Discussão em 'Angular' iniciado por Max, Dezembro 11, 2024.

  1. Max

    Max Guest

    I have a http.get method that gets a number. When http.get returns a number, I assign it to the variable ‘totalPages’. In the same method, I check if the value was assigned to this variable. Yes, the value was assigned. Then I exit this method and check this variable again for the previously assigned value, and this value is not there, the variable is empty. I don’t know what’s going on.

    My algorithm of actions is as follows.

    I have a page http://localhost:4200/user/3 from this page I go to the main page http://localhost:4200 and refresh it to reset all application data.

    Then, by pressing the browser “back” button, I get to the page http://localhost:4200/user/3 and here I have the same problem.

    But if, while on this page http://localhost:4200/user/3 and refresh the browser, the problem does not occur. It only occurs when I do back. But first on the main page you need to refresh the page to reset all application data, and only then do back.

    Perhaps the problem is due to the method being triggered later. But if I am on the page where the problem occurs http://localhost:4200/user/3 and refresh it, then the problem does not occur, and the method is triggered in turn.

    How to solve this problem is not entirely clear and in general I do not understand why this happens.

    class UserComponent

    Please explain how to fix this problem?

    export class UserComponent implements OnInit {

    totalPages: number = 0;


    constructor(private httpRS: HttpRequestService) {


    }


    ngOnInit(): void {

    this.httpRS.getAdsPageById().subscribe({
    next: data => {

    let responseData: any = data;
    this.totalPages = responseData.body.page.totalPages;

    console.log(this.totalPages, ' === totalPages 1') // 7

    }
    });

    console.log(this.totalPages, ' === totalPages 2') // 0

    }

    }


    class HttpRequestService

    export class HttpRequestService {

    constructor(private http: HttpClient) { }


    public getAds(): Observable<HttpResponse<any> | HttpErrorResponse> {
    return this.http.get<HttpResponse<any> | HttpErrorResponse>(`http://localhost:8080/posts`,
    {observe: 'response'});
    }

    }


    [​IMG]

    Continue reading...

Compartilhe esta Página