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":
I don't understand, I have the data and I can't use it. Even the most obvious indications are welcome.