I am currently facing an issue with retrieving data from a SQL server table using http.get within the constructor of an Angular component 5. While I am able to assign the retrieved data to a component property inside the subscribe method, the value becomes "undefined" when I try to access it later on. Here is the code snippet and the output I am encountering:
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 has a value
}, error => console.error(error));
console.log(this.topics); // It no longer has a value - it is undefined
}
}
Displaying "Chrome DevTools":
I am puzzled as to why I have the data but cannot utilize it. Any assistance in resolving this issue would be greatly appreciated.