My goal here is to utilize the variables retrieved from the route to determine which blog to access from the JSON file. The JSON file consists of an array of sections, each containing an array of blogs.
Although the code works flawlessly when I manually set id1 and id2 as 1 and 2 in the
this.blog=data[this.id1].blogs[this.id2];
line,
I encounter an error stating
TypeError:_data_json__WEBPACK_IMPORTED_MODULE_2___namespace[this.id1] is undefined
without any modifications.
import { Component, OnInit } from '@angular/core';
import * as data from '../data.json';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.css']
})
export class PostComponent implements OnInit {
id1;
id2;
sub;
blog;
constructor(
private _Activatedroute: ActivatedRoute,
private _router: Router
) {}
ngOnInit() {
this.sub = this._Activatedroute.paramMap.subscribe(params => {
console.log(params);
this.id1 = Number(params.get('id1'));
this.id2 = Number(params.get('id2'));
this.blog = data[this.id1].blogs[this.id2];
});
}
}
Even when substituting id1 and id2 with other variables, the same error persists.
edit: I made a change from
import * as data from '../data.json';
to const data=require('../data.json');
, and it provided the correct outcome. However, the reason behind this behavior eludes me, so I welcome further discussion on this topic.