I am just starting my journey with Angular 2 and observables, but I decided to dive right in. After installing angular-cli, I set up a simple test project.
My goal was straightforward - I wanted to read data from a json file and work with it inside a component (initially planning to use a service later on).
To start off, I created a json file in the assets/json folder (testjson.json):
{
"teststring": "test works"
}
Next, I imported http from Angular and the rxjs map functionality into my content.component.ts file:
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Component({
selector: 'app-content',
templateUrl: './content.component.html',
styleUrls: ['./content.component.css']
})
export class ContentComponent implements OnInit {
title: string = "Default";
data;
constructor(private http:Http) {
http.get('assets/json/testjson.json').map(res => res.json()).subscribe(data => {this.data = data; this.title = data.teststring; console.log(this.data);});
}
ngOnInit() {
}
}
So far, so good - the app displays the following:
app works!
test works [object Object]
However, I want to utilize this data throughout the entire component, not just within the constructor. When I attempt to console.log "this.data" outside of the constructor (inside the ngOnInit function), the console shows undefined.
I understand that this issue is related to asynchronous loading, but I'm unsure how to make the app wait for this.data to be populated.
I would greatly appreciate any guidance you can provide. In the future, I plan to implement a service to handle this type of functionality, allowing multiple components to access the data.
Thank you in advance!