My JSON file contains information about various pages:
{
"pagesList":
[
{
"pageUrl": "index",
"imgUrl": "homepage",
"imgNumber": 17
},
{
"pageUrl": "second",
"imgUrl": "secondimage",
"imgNumber": 10
}
]
}
In order to retrieve the value 17 (from "imgNumber": 17) as a variable in the component code without displaying it in the template, I need to get data from the JSON file using the img-carousel.service.ts
:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ImgCarouselService {
constructor(private http: HttpClient) { }
getPagesJson() {
return this.http.get('/assets/from-server/pages.json');
}
}
Next, I transform the JSON data into an array of objects in the component testzone.component.ts
:
import { Component, OnInit } from '@angular/core';
import { ImgCarouselService } from '../img-carousel.service';
import {Pages} from '../pages';
@Component({
selector: 'app-testzone',
templateUrl: './testzone.component.html',
styleUrls: ['./testzone.component.css'],
providers: [ImgCarouselService]
})
export class TestzoneComponent implements OnInit {
pageParams: Pages[] = [];
constructor(private imgCarouselService: ImgCarouselService) {
}
ngOnInit() {
this.imgCarouselService.getPagesJson().subscribe(data => this.pageParams = data["pagesList"]);
}
//imgnum = this.pageParams[0]["imgNumber"];
}
I also create a class Pages
to handle the data:
export class Pages {
pageUrl: string;
imgUrl: string;
imgNumber: number;
}
Finally, I display the data on the screen using the template testzone.component.html
:
pageParams = {{pageParams | json}}
pageParams[0].imgUrl = {{pageParams[0]?.imgUrl}}
<ul *ngFor="let item of pageParams">
<li>imgUrl = {{item?.imgUrl}}</li>
<li>pageUrl = {{item?.pageUrl}}</li>
<li>imgNumber = {{item?.imgNumber}}</li>
</ul>
However, when trying to assign the value 17 (from "imgNumber": 17) to a new variable in the component code:
imgnum = this.pageParams[0]["imgNumber"];
, the screen goes blank after refreshing the browser. There are no error messages in the IDE, just a blank screen.
How can I access specific data in the component code without displaying it in the template? Any suggestions would be appreciated. Thanks.