I have a project on Angular 18. I need to update the html page, regarding response value of ngOnInit(). When I test my code as below, I can see the test and maxPage values of ngOnInit() on html component as test = "ngOnInit" and maxPage = 2.
main.ts
@Component({
selector: 'app-main',
standalone: true,
imports: [],
templateUrl: './main.component.html',
styleUrl: './main.component.css'
})
export class MainComponent {
maxPage = 0;
test!: string;
constructor(){
this.maxPage = 1;
this.test = "constructor"
}
ngOnInit() {
this.maxPage = 2;
this.test = "ngOnInit"
}
}
main.html
<p>main works!</p>
<p> Max Page number : {{maxPage}}</p>
<p> Test : {{test}}</p>
However, if I change the logic with httpClient in ngOnInit() as follows, the values on html come from constructor as test = "constructor" and maxPage = 1, but still I need values from ngOnInit:
ngOnInit() {
this.subscription = this.dataTransferService.data$.subscribe(data => {
console.log(data);
if (data !== null)
{
this.postMicroservice.getAllJonPosts().subscribe((data:any) =>{
let result = JSON.parse(JSON.parse(JSON.stringify(data)).data);
this.maxPage = result.maxPageNumber;
this.test = "ngOnInit";
});
}
});
}
I can validate my results in ngOnInit using console.log(). Could you please help me for showing the ngOnInit values on html. Thank you in advance for your time and help.
2
Answers
You might have an error in the browser console, you can check that.
For now try parsing the response only if its a string then try to access the property.
Also you can use typescript safe access
?.
to prevent "error accessing properties of undefined" issues.You are not getting updated values because those two lines in which you update values are unreachable. Do console log inside getAllJonPosts subscription to make sure this service is emitting data (most probably not)
Check my stackblitz demo here and it is working fine