I'm new to Angular 6 and I'm trying to iterate over an array of objects but it's producing nothing. People online are talking about subscribing to the observable and I can't figure out how to do that if it's the problem.
This is my component:
import { Component, OnInit } from '@angular/core';
import { Topic } from '../topic';
import { TopicFetcherService } from '../topic-fetcher.service'
@Component({
selector: 'app-topics',
templateUrl: './topics.component.html',
styleUrls: ['./topics.component.css']
})
export class TopicsComponent implements OnInit {
constructor( private topicFetcher: TopicFetcherService) { }
topics: Topic[];
ngOnInit() {
// this grabs my topics from my http service
this.processTopics(this.topicFetcher.getData());
}
processTopics(rawTopics: Topic[]) {
console.log(rawTopics); // this works
rawTopics.forEach(topic => {
console.log(topic.id); // this does not work ?
});
}
}
I don't understand why console.log(rawTopics) works but if you try to iterate over it, you have to get involved with observables. That seems a little heavy handed.
EDIT:
This is my topic-fetcher service. It currently just .get's a .json file in assets:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Topic } from './topic';
@Injectable({
providedIn: 'root'
})
export class TopicFetcherService {
constructor(private http: HttpClient) { }
topics: Topic[];
getData(): Topic[] {
this.topics = [];
let index = 1;
this.http.get('assets/topics.json')
.subscribe(data => {
for (const key in data) {
let topic = new Topic();
topic.id = index;
topic.title = data[key].topic;
topic.description = data[key].narrative;
topic.type = data[key].type;
topic.dataset = data[key].dataset;
this.topics.push(topic);
index++;
}
});
return this.topics;
}
}