1

A simple Http.Get, and I missing something but I don't realize what is't.

this.http.get<Reserve[]>(this.url).
subscribe(result => {
    this.reserves = result;
        console.log('Data from source:' , result , 'Data when load:' , this.reserves)
    },
    error => console.error('Loading reserve error', error));

console.log('Data after Load', this.reserves);

Console results indicate that the data has been actually capture (Data from source and Data when load):

Console results

Data from source: (5) [{…}, {…}, {…}, {…}, {…}]0: {id: 1, restaurantId: 1, restaurant: {…}, dateReserve: "2020-05-17T21:00:00", ranking: 1, …}1: {id: 2, restaurantId: 2, restaurant: {…}, dateReserve: "2020-05-18T20:00:00", ranking: 1, …}2: {id: 3, restaurantId: 4, restaurant: {…}, dateReserve: "2020-05-20T19:00:00", ranking: 4, …}3: {id: 4, restaurantId: 4, restaurant: {…}, dateReserve: "2020-05-21T20:00:00", ranking: 5, …}4: {id: 5, restaurantId: 4, restaurant: {…}, dateReserve: "2020-05-17T21:00:00", ranking: 2, …}length: 5__proto__: Array(0) 
Data when load: (5) [{…}, {…}, {…}, {…}, {…}]0: {id: 1, restaurantId: 1, restaurant: {…}, dateReserve: "2020-05-17T21:00:00", ranking: 1, …}1: {id: 2, restaurantId: 2, restaurant: {…}, dateReserve: "2020-05-18T20:00:00", ranking: 1, …}2: {id: 3, restaurantId: 4, restaurant: {…}, dateReserve: "2020-05-20T19:00:00", ranking: 4, …}3: {id: 4, restaurantId: 4, restaurant: {…}, dateReserve: "2020-05-21T20:00:00", ranking: 5, …}4: {id: 5, restaurantId: 4, restaurant: {…}, dateReserve: "2020-05-17T21:00:00", ranking: 2, …}length: 5__proto__: Array(0) 

But 'Data after Load' is UNDEFINED

bpf
  • 11
  • 3
  • 'Data after Load' actually gets prints first, before the response is obtained in the subscription . – rickz Sep 13 '20 at 03:12
  • 1
    An http request is an asynchronous function. The 'Data after Load' isn't going to wait for the async function to complete. So of course it will be undefined. – Wesley Sep 13 '20 at 03:42
  • The variable `this.reserves` is assigned asynchronously. It **cannot** be accessed synchronously. Any statements that depend on it directly should be inside the subscription. In other words, you need to subscribe to the observable where the `this.reserves` is required. – ruth Sep 13 '20 at 07:42

2 Answers2

0

You Can Call Your Method Inside Subscribe To Do What You Want to Do After Load Data:

Angular 2+ wait for subscribe to finish to update/access variable

 export class myClass {
  myVariable: any;

  myFunction() {
    this.myService.getApi().subscribe(data => {
      this.myVariable = data;
      this.update()
    });

    this.update()
  }

  update(){
    console.log(this.myVariable);
  }
}

Or Return Obsevable To Subscribe EveryWhere You Want to Use Result:

Angular 6 wait for subscribe to finish

getNumber(value) {
    return this.myService.getApi(value).pipe(tap(data => {
        this.myVariable = data;
    }));
}

And in your set method

set() {
    if (this.value == 1) {
      this.getNumber(firstNumber).subscribe(() => {
        this.newVariable = this.myVariable;
      });
    }
    else {
      this.getNumber(secondNumber).subscribe(() => {
        this.newVariabe = this.myVariable + 1;
      });
   }
};

Or Use await to wait until result is ready:

Angular 2+ wait for method / observable to complete

  async isAuthenticated(){
     const response = await this.http.get('/login/authenticated').toPromise();
     return response.json();
  }

async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    this.loginStatus = await this.loginService.isAuthenticated();

    console.log("LOGGED IN STATUS: " + this.loginStatus);

    if (this.loginStatus == true){
        return true;
    }

    // not logged in so redirect to login page with the return url
    this.router.navigate(['/layout/login'], { queryParams: { returnUrl: state.url } });    
}
Masoud Bimmar
  • 6,941
  • 4
  • 30
  • 33
0

You are getting undefined because it is an async method that will not wait to get a response from the server. try to use async/await or print the value inside then block

    this.http.get<Reserve[]>(this.url).subscribe(result => {
        this.reserves = result;
        console.log('Data from source:' , result , 'Data when load:' , this.reserves)
        console.log('Data after Load', this.reserves);
    },
    error => console.error('Loading reserve error', error));
sanjay
  • 514
  • 2
  • 5
  • 14