An Angular component to show country GDP

The show-gdp component takes the country data from the first screen, makes a call to the World Bank API, and fetches the data in a JSON format, before finally sending it to the chart module to render the graph. This component looks as follows:

@Component({
selector: 'jhi-show-gdp',
templateUrl: './show-gdp.component.html',
})
export class CountryGDPComponent implements OnInit {
currentCountry: ICountry;
data: IGdpData[];
preGDPUrl = 'http://api.worldbank.org/v2/countries/';
postGDPUrl = '/indicators/NY.GDP.MKTP.CD?format=json&per_page=' + 10;
year = [];
gdp = [];
chart = [];
noDataAvailale: any;
constructor(
private activatedRoute: ActivatedRoute,
private httpClient: HttpClient
) {
this.activatedRoute.data.subscribe(data => {
this.currentCountry = data.country;
});
}
ngOnInit() {
const gdpUrl = this.preGDPUrl + this.currentCountry.code
+ this.postGDPUrl;
this.httpClient.get(gdpUrl).subscribe(res => {
this.noDataAvailale = true;
const gdpDataArr = res[1];
if ( gdpDataArr ) {
this.noDataAvailale = false;
gdpDataArr.forEach(y => {
this.year.push(y.date);
this.gdp.push(y.value);
});
this.year = this.year.reverse();
this.gdp = this.gdp.reverse();

this.chart = new Chart('canvas', {
type: 'line',
data: {
labels: this.year,
datasets: [
{
data: this.gdp,
borderColor: '#3cba9f',
fill: true
}
]
},
options: {
legend: {
display: false
},
scales: {
xAxes: [{
display: true
}],
yAxes: [{
display: true
}],
}
}
});
}
});
}
}

In the constructor of this component, we are getting the selected country from the Angular router. In the resolve() method of the CountryGDPResolve class, we are fetching the country object from the ID parameter in the URL, and this object is then available to this component through the router, because we have provided a resolve configuration to this component in countryGDPRoute, as follows:

    {
path: 'showGDP/:id',
component: CountryGDPComponent,
resolve: {
country: CountryGDPResolve
}
}

Once we get the country information, we will make our calls to the World Bank API. The URL for this is as follows:

http://api.worldbank.org/v2/countries/IND/indicators/NY.GDP.MKTP.CD?format=json&per_page=10.

In this URL, the country code is inserted dynamically, from the country data that is given by the router. The per_page attribute returns the GDP data for that many numbers of years. The preceding example shows the last ten years' worth of GDP data for the country India. After getting the JSON data, we are iterating and preparing two arrays, year and gdp, and passing them to the chart module to generate a chart on the screen. The chart module can be installed as a node module, with the npm install chart.js command.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.131.13.37