Angular newActualites array is not populated on the function call on ngOnInit,

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>

Speech to Text API in Angular

I’m using web speech API in my angular application for voice to text functionality. I’m able to get the text which user has spoken when they click on stop recording.

I have a use case where i need to show the interim data, whenever a user is speaking whatever they speak should be populated on the screen. It should appear as if dynamically shown on the screen.

Do we have any event listener to listen for this activity.

Thanks for your help in advance.

How to display two unsynchronized datasets in chart.js

I have two datasets (x: time, y: value) and I want to display them in a single line chart.
The problem is that the datasets aren’t synchronized (one time, two values).

Is it possible to make a chart where for each point on the x-axis there is only one value but two datasets are displayed?

For illustration, this is the result I want:
illustration of the desired chart

I tried to make the chart like this, but the X axis didn’t even draw. The datapoints had the correct Y value but their X value appeared to be undefined

function drawChart() {
    const ctx = document.getElementById('chart1');
    chartObjects.push(new Chart(ctx, {
        type: 'line',
        data: {
            datasets: [{
                label: 'value 0',
                data: sensorModulesDict[sensorIDs[0]].map(item => ({ x: item.time, y: item.co2 })),
                borderColor: '#81D929',
            },
            {
                label: 'value 1',
                data: sensorModulesDict[sensorIDs[1]].map(item => ({ x: item.time, y: item.co2 })),
                borderColor: '#E67417',
            },
            ]
        },
        options: {
        }
    }));
} 

Result of my attempt:
result of my attempt

Getting the array of {x,y} objects is a bit complicated due to other aspects of my code, but I checked in console and the array is correct.
console output of my data array

Blank page when integrating firebase authentication

I am new to firebase. I am trying to add firebase authentication to my web application. When I import firebase (and add the authentication command into the code file to be executed on click of the sign in button), the webpage turns blank. Nothing shows up on the webpage, but the code compiles just fine. I have tried a couple different import commands for the firebase.js file, but none have fixed the problem. Below is the firebase.js file and the corresponding login.js login page file.

import firebase from 'firebase/compat/app';

const firebaseConfig = {
    apiKey: "***",
    authDomain: "***",
    projectId: "***",
    storageBucket: "***",
    messagingSenderId: "***",
    appId: "***",
    measurementId: "***"
  };

  const firebaseApp = firebase.initializeApp(firebaseConfig);
  const db = firebaseApp.firestore();
  const auth = firebase.auth();
  const provider = new firebase.auth.GoogleAuthProvider()

  export {auth, provider};
  export default db;
  
import React from 'react';
import './Login.css';
import { Button } from '@mui/material'
import { auth, provider } from './firebase'

function Login() {
 const signIn = () => {
     auth.signInWithPopup(provider).catch((error) => alert(error.message));

 }

  return (
    <div className = "login"> 
    <h1> Welcome to Chatlytic</h1>

    <div className="login__logo">

    </div>
    <Button onclick = {signIn}> Sign In</Button>
    </div>
  )
}

export default Login

implementing AST tranformation

I have implemented an AST transformation and modification of JS in java using Mozilla’s Rhino. but it seems that Rhino doesn’t fully support ES6 syntax and couldn’t parse the JS code.
Hence, I am thinking of moving(migrating) to Graaljs, but couldn’t find any leads to implement it.
Is it possible to implement AST transformation using Graaljs’ polyglot api?

Any further assistance or references could be helpful.

javascript regex for string

I need to check that a string input contains exactly 2 special characters and 1 number.

is this the correct regex for this job?

(?=(.*[`!@#$%^&*-_=+'/.,]){2})

this is only checking special characters and not numbers.

I tried the regex above and it is not checking numbers

Do javascript switch statements do not allow passing of file locations within sub-folders?

I am unable to open files within sub-folder locations inside a switch statement which works just fine if the parent folders of both my javascript file and the target file are the same.

I have created a sidebar which has multiple components which i want to link to their respective html files . Previously i just dumped all the files in one folder and it was working

This worked just fine ….

 switch (this.textContent) {
    case "Calendar":
      fileToLoad = "calendar.html";
      break;
 
  }

but now when i created sub-folders and tried to declare them normally , its not working.

switch (this.textContent) {
    case "Calendar":
      fileToLoad = "Components/Calendar/calendar.html";
      break;
}

Am i doing something wrong here?

How to Use Multiple API for same purpose in Same Project

Due to reaching the hourly request allocation limit on my current external API, I’ve created multiple additional APIs. Now, I’m seeking a strategy to effectively manage these APIs in a sequential manner. How can I ensure a seamless transition between the APIs, utilizing them one by one, to prevent any disruptions in service while staying within the request limits of each API?

Please Give Some Code so that I use API_1,API_2,API_3 for same purpose multiple time in same code in nodejs

The Single-Spa bundled JavaScript file is exposing my secret keys

I wanted to understand more about a security risk that I am facing within my Single-spa and React application architecture.

Currently, I use the Node.js module ‘DOTENV’ to load environment variables from a .env file.
I am using this method to keep sensitive information separate to my source code, as well as making it easier to manage different configurations across different environments.

The issue: when my React application is bundled using Single-spa, all the environment variables, including my secret keys, are embedded within the resulting JavaScript file. This means that if someone were to access the JavaScript file directly from the UI, they would be able to see the actual values of my secret keys. As you can imagine, this poses a significant security concern.

I am unsure how to prevent the exposure of my sensitive information like this, may you please help with some suggestions?

I have tried to move all my environment variables (example: process.env.SECRET_KEY) from the UI code, to a NODEJS server, which I believe should hide the secret keys from the UI. I have been advised by my coworkers that this solution will prevent users from accessing the secrets from the UI, but it would make my NODEJS server more vulnerable to attackers, as an experienced hacker could now just attack my NODEJS server instead. If moving my environment variables to the NODEJS server is my best solution so far, how do I prevent a hacker from being able to get my env variables from the NODEJS server? and are there any other suggestions I could learn more about to prevent this?

React keeps calling a function repeatedly [duplicate]

I have a react page with a function to fetch data from API in a loop. The loop terminates when a certain condition is met. Till here everything keeps working as expected.

export default function Data() {
    ...
    ...
    needMore = true
    var loadData = async () => {
        ...
        while (needMore) {
            var result = await fetch('http://localhost:6000/api/data');
            dataRow = await result.json();
            addItems(offset, dataRow);
            if (dataRow.length < bacthSize) {
                ...
                needMore = false
                break;
            }
        };
        console.log("Completed.");
    }
    loadData();


    return (
        <div className="ag-theme-balham" style={{ width: '100%' }}>
            <Stack spacing={2}>
                <AgGridReact
                    ...
                defaultColDef={defaultColDef} />
            </Stack>
        </div>
    );
}

However, the issue is that the function loadData repeatedly keeps getting called hence creating a indefinite loop.

I can see the complete data has been fetched once and in console I can also see Completed. which I am logging, but immediately that the function gets called again, which I am not sure why and how can I stop this?

How can the client force the browser to reload cache only for errors like 429?

I’m accessing servers that are not under my control. They direct the browser to cache responses. I know I can override this with fetch(url, { cache: "reload" }), but is there a way to only reload requests known to have failed? I want to use the cache if a successful non-stale response exists, and always reload for unsuccessful responses.

I was surprised to discover that 429’s are cached. I’d also like to learn the reasoning behind that.

How to form an array using series of dataset Id values you’ve collected from a div

The dataset Id is attached to the imageLet’s say for instance I’ve attached dataset Id values to a series of div’s and these values are different from one another, if I want to collect these values and form an array with them how do it do it?

I already tried looping through them since they are all divs with the same class name,but it gives me back the values on individual array and not collectively into one array. I can’t use array.from() cos it would just turn the string into separate characters and form an array with them. What do you all suggest I do?

JavaScript Functions Running Randomly

I have a button, and a counter. The counter is assigned count. When you click the button counterPlusElem, the count increases. You can buy upgrades that take away some of your count, but make it so on each click of counterPlusElem, it adds 2 to count instead of 1. The background-image property changes once a certain count threshold has been met, or that’s the goal. Once the image has changed from car1.png to car2.png, I don’t want it to be able to switch back. The problem is that once you have enough count, you reach car4.png, then it starts reverting again.

Thanks.

Code :

function levelUp() {
        if (count >= 0 && count < 10) {
            imageCount1++;
            console.log("imageCount1 + 1");
        }
        if (imageCount1 > 0 && imageCount2 < 1) {
            counterPlusElem.style.backgroundImage = "url('car1.png')";
            imageCount2 = 0; // Reset other image counts
            imageCount3 = 0;
            imageCount4 = 0;
            imageCount5 = 0;
            imageCount6 = 0;
            imageCount7 = 0;
        }

        if (count >= 10 && count < 100) {
            imageCount2++;
            console.log("imageCount2 + 1");
        }
        if (imageCount2 > 0 && imageCount3 < 1) {
            counterPlusElem.style.backgroundImage = "url('car2.png')";
            imageCount1 = 0; // Reset other image counts
            imageCount3 = 0;
            imageCount4 = 0;
            imageCount5 = 0;
            imageCount6 = 0;
            imageCount7 = 0;
        }
        if (count >= 100 && count < 1000) {
            imageCount3++;
            console.log("imageCount3 + 1");
            imageCount2 = 0;
        }
        if (imageCount1 < 1 && imageCount2 < 1 && imageCount3 > 0 && imageCount4 < 1) {
            counterPlusElem.style.backgroundImage = "url('car3.png')";
            imageCount1 = 0; // Reset other image counts
            imageCount2 = 0;
            imageCount4 = 0;
            imageCount5 = 0;
            imageCount6 = 0;
            imageCount7 = 0;
        }
        if (count >= 1000 && count < 10000) {
            imageCount4++;
            console.log("imageCount4 + 1");
            imageCount3 = 0;
        }
        if (imageCount1 < 1 && imageCount2 < 1 && imageCount3 < 1 && imageCount4 > 0 && 
imageCount5 < 1) {
            counterPlusElem.style.backgroundImage = "url('car4.png')";
            imageCount1 = 0; // Reset other image counts
            imageCount2 = 0;
            imageCount3 = 0;
            imageCount5 = 0;
            imageCount6 = 0;
            imageCount7 = 0;
        }
        if (count >= 10000 && count < 50000) {
            imageCount5++;
            console.log("imageCount5 + 1");
            imageCount4 = 0;
        }
        if (imageCount1 < 1 && imageCount2 < 1 && imageCount3 < 1 && imageCount4 < 1 && 
imageCount5 > 0 && imageCount6 < 1) {
            counterPlusElem.style.backgroundImage = "url('car5.png')";
            imageCount1 = 0; // Reset other image counts
            imageCount2 = 0;
            imageCount3 = 0;
            imageCount4 = 0;
            imageCount6 = 0;
            imageCount7 = 0;
        }
        if (count >= 50000 && count < 100000) {
            console.log("imageCount6 + 1");
            imageCount6++;
            imageCount5 = 0;
        }
        if (imageCount1 < 1 && imageCount2 < 1 && imageCount3 < 1 && imageCount4 < 1 && 
imageCount5 < 1 && imageCount6 > 0 && imageCount7 < 1) {
            counterPlusElem.style.backgroundImage = "url('car6.png')";
            imageCount1 = 0; // Reset other image counts
            imageCount2 = 0;
            imageCount3 = 0;
            imageCount4 = 0;
            imageCount5 = 0;
            imageCount7 = 0;
        }
        if (count >= 100000 && count < 200000) {
            imageCount7++;
            console.log("imageCount7 + 1");
            imageCount6 = 0;
        }
        if (imageCount1 < 1 && imageCount2 < 1 && imageCount3 < 1 && imageCount4 < 1 && 
imageCount5 < 1 && imageCount6 < 1 && imageCount7 > 0) {
            counterPlusElem.style.backgroundImage = "url('car7.png')";
            imageCount1 = 0; // Reset other image counts
            imageCount2 = 0;
            imageCount3 = 0;
            imageCount4 = 0;
            imageCount5 = 0;
            imageCount6 = 0;
        }
    }

Angular 12 How to isolate scope of property when parent and child component extend same base component

I have an abstract base class called ScreenBaseComponent:

export abstract class ScreenBaseComponent implements OnInit, OnDestroy {
   public trackId: number;
}

I have a parent component that extends the ScreenBaseComponent:

export class ParentComponent extends ScreenBaseComponent implements OnInit, OnDestroy {

}

One of the child components in ParentComponent called ChildComponent also extends ScreenBaseComponent:

export class ChildComponent extends ScreenBaseComponent implements OnInit, OnDestroy {
 public trackId: number;

 ngOnInit() {
        super.ngOnInit();
        this.trackService.getTrackDesigns(this.gridId).subscribe((data) => {            
            data.map((eachTrac) => {
                if (eachTrac.name == this.TracName) {
                    this.trackId = eachTrac.id;
                }
            });
        });
    }
}

As per the requirement, change in trackId, triggers an event and the grid is reloaded. When I change the trackId in the child component the grid in child page is reloaded which is good. The issue is, the trackId in parent component also changes. Is there a way to isolate the scope of trackId within each component?

Trying to understand the issue here. Thanks in advance.