I am currently developing an Angular 2 application and encountering challenges with using JSON data, whether local/mocked or fetched via HTTP, and displaying it on a component. I have created an injectable service that handles fetching/mocking the data:
import { Injectable } from 'angular2/core';
@Injectable()
export class TestService {
testString: string = "";
testDetails: string = "";
constructor() { }
getTestDetails(): Promise<string> {
this.testDetails = {
"status": "success",
"message": "Data save successful",
"data": {
"Random_Data_1": "Random Data 1",
"Random_Data_2": "Random Data 2"
}
};
return Promise.resolve(JSON.stringify(this.propertyDetails));
}
}
I also have a component that utilizes the service through Dependency Injection:
import { Component, OnInit } from 'angular2/core';
import {TestService} from "./test.service";
@Component({
selector: 'test',
templateUrl: './test.component.html',
styleUrls: []
})
export class TestComponent implements OnInit {
testDetails: string = "";
constructor(private testService: TestService) { }
ngOnInit() {
this.display();
}
display(): void {
this.testService.getTestDetails()
.then(
testDetails => {
this.testDetails = JSON.parse(testDetails);
},
errorMessage => {
console.error("An error occurred while trying to retrieve test details");
console.error(errorMessage);
}
);
}
}
The HTML structure of the component is as follows:
<div class="content">
<p> Test Details </p>
<p> {{ testDetails.data.Random_Data_1 }} </p>
</div>
However, I am facing issues with the HTML displaying the items in the testDetails JSON. While testing with md-tabs, the first attempt fails but subsequent tabs work correctly. Additionally, when the error occurs, ngOnInit is called twice. The problem seems to be related to the data types in the object.
I am aware that creating a dedicated Details class and defining testDetails as type Details could resolve the issue by mapping the JSON data into the class. Nonetheless, I prefer working with generic data and only need to extract specific components from it. Is there a way to read the JSON data without creating separate classes for each scenario?
I have prepared a basic Plunker setup showcasing the main components. Although the code runs flawlessly on my local machine until accessing the JSON data in the HTML causes a browser error. The skeleton code does not run as expected on Plunker, but it still represents the app's structure and data flow. Access the Plunk link here: Plunker with the basic setup
Seeking advice on the best approach to address this challenge and understand the standard/best practice for handling such scenarios.