-1

I'm trying to retrieve data from a sql server table using http.get used inside the constructor of an angular component 5. The data I can assign to a component property inside the subscribe, but when I look for it to use the property value I get a "undefined" value. Below is the code and the output obtained:

topic.service.ts

import { Injectable, Inject, Input, OnChanges, SimpleChanges  } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { AuthService } from '../auth.service';

@Injectable()
export class TopicService {
  topics: Topic[];
  name: string;

  constructor(private http: HttpClient,
    @Inject('BASE_URL') private baseUrl: string,
    private router: Router,
    public auth: AuthService) {    

    http.get<Topic[]>(baseUrl + 'api/Topic/List').subscribe(result => {
      this.topics = result;
      console.log(this.topics);         // It is valued
    }, error => console.error(error));

console.log(this.topics);     // It is no longer valued - it is undefined

  }

}

As from "Chrome DevTools":

enter image description here

I don't understand, I have the data and I can't use it. Even the most obvious indications are welcome.

סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68
Paolo
  • 13
  • 4
  • You're seeing this because the second `console.log` in the code is actually running before the first `console.log` in the code. This happens due the fact that http calls are asynchronous. `this.topics` will be undefined until the http call completes, and the value gets assigned inside the `subscribe`. – R. Richards Jun 30 '19 at 22:02
  • So how can I intercept the data and store it in the property? – Paolo Jul 01 '19 at 09:45
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Dec 30 '19 at 14:45

1 Answers1

1

It is no longer valued - it is undefined

If you look at your image, it's actually not yet defined/"valued". You can see this is the case because undefined is logged to the console before the array.

get is asynchronous so the callback in subscribe hasn't yet run, hence the behavior.

ChiefTwoPencils
  • 13,548
  • 8
  • 49
  • 75