On the function populateNewActualites() {} this.newActualites.length is displayed corectly but on ngOnInit is always 0
Definition of the variable:
export class AccueilComponent implements OnInit {
modalVisible: boolean = false;
modalDisplayCount: number = 0;
actualites: Actualite[];
newActualites: Actualite[] = [];
}
ngOnInit this.getActualites(); //With this function im getting all the actualites.
And with the checkForNewNews function we are populating the newActualites array.
ngOnInit() {
this.authentificationService.getInfosUtilisateur$()
.subscribe(infosUser => {
this.displayExternalTools = !!infosUser.profile;
if (infosUser.profile !== undefined && infosUser.profile !== 'UTL_ANONYME') {
this.getActualites(); //With this function im getting all the actualites.
}
}
);
// Subscribe to the newNewsAdded event
this.actualiteService.newActualite.subscribe((newActualiteItem: Actualite) => {
this.checkForNewNews(newActualiteItem);
});
getActualites function:
getActualites() {
this.actualiteService.getAll().subscribe(actualites => {
this.actualites = actualites
});
}
checkForNewNews function with populateNewActualites function for getting only the new news.
checkForNewNews(newNewsItem: Actualite) {
const initialNewsLength = this.actualites.length;
this.actualites.push(newNewsItem);
const updatedNewsLength = this.actualites.length;
if (updatedNewsLength > initialNewsLength) {
this.populateNewActualites();
this.accueilModalService.resetModalDisplayCount();
}
}
populateNewActualites() {
this.newActualites = this.actualites.filter(newsItem => {
if (newsItem.dateCreation != null) {
const parts = newsItem.dateCreation.split('/');
const formattedDateString = `${parts[1]}/${parts[0]}/${parts[2]}`;
const dateObject = new Date(formattedDateString);
const dateObjectWithoutTime = new Date(dateObject.getFullYear(), dateObject.getMonth(), dateObject.getDate());
const connectionDateWithoutTime = new Date(this.connectionDate.getFullYear(), this.connectionDate.getMonth(), this.connectionDate.getDate());
return dateObjectWithoutTime >= connectionDateWithoutTime;
}
});
console.log(this.newActualites);
}
In the end, we have this conditional rendering modal to display in the first place only the actualites array, and after we add a new news, we only need to display the newActualites array. The problem is that the newActualites array is never displayed, even though the array is populated with succes in the destinated functions.
<div class="slider-modal-container" *ngIf="modalVisible">
<ng-container *ngIf="newActualites.length > 0">
<!-- Show modal with newActualites array -->
<app-accueil-modal [actualitesItems]="newActualites" (closeModal)="closeModal()"></app-accueil-modal>
</ng-container>
<ng-container *ngIf="newActualites.length === 0">
<!-- Show modal with old actualites array -->
<app-accueil-modal [actualitesItems]="actualites" (closeModal)="closeModal()"></app-accueil-modal>
</ng-container>
</div>