Getting NullInjectorError: No provider for function(options) in Angular 17

I’m a beginner in Angular (17 version). I’m getting error:
ERROR Error [NullInjectorError]: R3InjectorError(Standalone[_LoginPageComponent])[function(options) { -> function(options) { -> function(options) { -> function(options) { -> function(options) {]:
[1] NullInjectorError: No provider for function(options) {!
while adding private router: Router to constructor() in login-page.component.ts.

login-page.component.ts

import { CommonModule} from '@angular/common';
import { Component, OnInit} from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { AuthService } from '../shared/layouts/services/auth.service';
import { Subscription } from 'rxjs';
import { Router } from 'express';

@Component({
  selector: 'app-login-page',
  standalone: true,
  imports: [ReactiveFormsModule, CommonModule],
  templateUrl: './login-page.component.html',
  styleUrl: './login-page.component.css'
})
export class LoginPageComponent implements OnInit{
  form : FormGroup
  aSub: Subscription
  constructor(private auth: AuthService, private router: Router) {
  }

  ngOnInit(): void {
    this.form = new FormGroup({
      email: new FormControl(null, [Validators.email, Validators.required]),
      password: new FormControl(null, [Validators.minLength(6), Validators.required])
    })
  }
  

  onSubmit() {
    this.form.disable()

    this.aSub = this.auth.login(this.form.value).subscribe({
      next: (result) => {
      },

      error: (error) => {
        console.log(error)
        this.form.enable()
      }
    })
  }
}

app.config.ts

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { provideHttpClient, withFetch } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes), provideClientHydration(), provideHttpClient(withFetch())]
};

auth.service.ts

import { Injectable } from "@angular/core";
import { User } from "../interfaces";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
@Injectable({
    providedIn: 'root'
})
export class AuthService {

    constructor(private http: HttpClient) {    
    }

    register() {

    }

    login(user: User): Observable<{token: string}> {
        return this.http.post<{token: string}>('http://localhost:5000/api/auth/login', user)
    }
}

Help me figure out what the problem is. Thanks!

Is anyone interested in doing team project related to Full Stack web development?

I’m Anwar, a Bachelor’s Degree student. I’m working on a full stack web application this summer that will be launched online. If we have a team with members handling frontend and backend coding, marketing, and other tasks, it will resemble a real industrial project and be more efficient.
If you know HTML, CSS, Js, React, Nodejs, MySQL, or any database, or you’re into marketing , we can work this out, we need someone in every field.

If you’re truly interested and committed to completing a project, we can form a team.
Here’s Joining Link to Slack: Join the Team
Thank you for your time.

Zoom into country

I’m trying to create a function that users can click on a country marker and the map will zoom into the country on React. However, the problem is the zoom level is different for different countries.

May I ask what is the best approach to zoom into a country (or a city or a poi) without hardcoding the zoom level for each country?

Currently this is my function which is nothing fancy. Just hard coding the zoom level.

  const flyToLocation = (latitude: number, longitude: number) => {
    mapRef.current?.flyTo({ bearing: 0, center: [longitude, latitude], zoom: 6 });
  };

I also tried with the example here https://visgl.github.io/react-map-gl/examples/zoom-to-bounds (and this is the library I am using). But the problem is that I still need to find the source for all countries and places and may align with the world view of Mapbox ( I actually prefer this way)

I found that https://visgl.github.io/react-map-gl/examples/geocoder can automatically zoom to the country by the result returned. But Geocoder is designed for human use by returning suggestions. I tried to look through the documentation but couldn’t find a build-in function for that.

May I ask how to deal with the problem? Any help is appreciated.

Why I can’t access state in window event handler?

I started learing react.js and developing a personal project now. I faced an issue and can’t find what’s wrong.

    const [open, setOpen] = useState(false);

    const handleScroll = () => {
        const { scrollHeight, clientHeight } = document.documentElement;

        console.log(open);
    };

    useEffect(() => {
        window.addEventListener('scroll', handleScroll);

        return () => {
            window.removeEventListener('scroll', handleScroll)
        }
        // eslint-disable-next-line
    }, []);

I set window scroll event handler and in handleScroll function, I want to show changing of open state. But it always shows me false even if I already changed it. Please help me what’s wrong.

I tried to pass open state to handleScroll, but it’s not working.

Chrome extention that download a page source code

This is my first chrome extension and here’s what I’ve managed to do.
The purpose of the extension is to download the source code of certain web pages and then refresh the page after a few seconds, and so on. This allows me to obtain the source code of these pages in text format every 10s and analyze them with software to detect any changes.
However, I have the impression that the browser is getting slower with time.
As this is the first time I’ve done javascript and browser extensions, I’m not sure I’ve done things correctly.
There are a few bits of code I don’t understand (those marked idk).

Here’s my code:

  • manifest.json
{
    "manifest_version": 2,
    "name": "YggRSS",
    "version": "1.0",
    "description": "Obtention du flux RSS depuis Yggtorrent",
    "permissions": ["tabs", "activeTab", "http://*/*", "https://*/*","downloads","management"],
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    },
    "browser_action": {
        "default_icon": "icon.png",
        "default_title": "YggRSS"
    }
}
  • background.json
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {    
    if (changeInfo.status == 'complete') {
        // Check if this is my target
        var expression = /mywebsite.*status/;
        if (expression.test(tab.url)) {
            
            // Get source code
            fetch(tab.url)
                .then(response => response.text())
                .then(data => {
                    // Check if sourcecode contains statusdetails
                    if (data.includes("atom-78")) {
                        // File name will be like sc_78_.txt for a page with the id 78
                        const match = tab.url.match(/id=(d+)/);
                        if (match && match[1]) {
                            const id = match[1];
                            const filename = 'sc_' + id + '_' + '.txt';

                            // Idk but it works
                            const blob = new Blob([data], { type: 'text/plain' });
                            const urlData = URL.createObjectURL(blob);

                            // Download the file
                            chrome.downloads.download({
                                url: urlData,
                                filename: filename,
                                conflictAction: 'uniquify',
                                saveAs: false
                            }, (downloadId) => {

                                // // After 8s, remload (don't works with more that 10s)
                                setTimeout(() => {
                                    chrome.tabs.update(tabId, { url: tab.url });
                                }, 8000);
                            });

                            // Idk but looks required
                            URL.revokeObjectURL(urlData);
                        } else {
                            alert('No id found.');
                        }
                    } else {
                        // Page load fail, reload
                        setTimeout(() => {
                                    chrome.tabs.update(tabId, { url: tab.url });
                                }, 10000);
                    }
                })
                .catch(error => {
                    alert('Unknown error', error);
                });
        }
    }
});

Prevent user from directing to the login when user is already logged in vuejs3

Network Manager

import axios from "axios";
import router from "@/router";
import { mixin } from "@/mixins/authMixin";

/**
 * Sends an API request using the specified method, endpoint, data, callback, and optional content type.
 *
 * @param {string} method - The HTTP method for the request (e.g., "get", "post").
 * @param {string} endpoint - The API endpoint to send the request to.
 * @param {object} data - The data to be sent with the request.
 * @param {function} callBack - The callback function to handle the response from the API.
 * @param {string} [contentType="application/json"] - The content type of the request (default is "application/json").
 */
const NetworkManager = {
  apiRequest: function (
    method,
    endpoint,
    data,
    callBack,
    contentType = "application/json",
  ) {
    const apiUrl = import.meta.env.VITE_APP_BACKEND_URL;
    console.log(mixin.data.userData);
    const URL = apiUrl + "/" + endpoint;

    let config = {
      headers: {},
      timeout: apiUrl.timeoutDuration,
    };

    config.headers["Content-Type"] = contentType;
    config.headers["Accept"] = "application/json";

    if (contentType === "multipart/form-data") {
      config.headers["onUploadProgress"] = (progressEvent) =>
        console.log(progressEvent.loaded);
    }

    axios.defaults.withCredentials = true;
    axios.defaults.withXSRFToken = true;
    //axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

    if (method === "post") {
      //   console.log(document.cookie)
      axios
        .post(URL, data, config)
        .then(function (e) {
          callBack(e.data);
        })

        .catch(function (error) {
          
          if (error.response) {
            // The request was made and the server responded with a status code
            // that falls out of the range of 2xx
            //Login logic here
            console.log(error.response.data);
            console.log(error.response.status);
            console.log(error.response.headers);
            if (
              error.response.status === 401 ||
              error.response.status === 419
            ) {
              console.log(
                "Unauthorized",
                mixin.data.userData.userDetails.email,
              );

              if (
                mixin.data.userData.userDetails.email == null ||
                mixin.data.userData.userDetails.email == ""
              ) {
                router.push("/login");
              } else {
                mixin.data.userData.reLoginWindow = true;
              }
            } else if (error.request) {
              // The request was made but no response was received
              let obj = {
                code: error.response.status,
                message: error.response.data,
              };
              callBack(obj);
              console.log("Error Request", error.request);
            }

            // Something happened in setting up the request that triggered an Error
          } else {
            let obj = {
              code: error.code,
              message: error.message,
            };
            callBack(obj);
            console.log("Error", error.message);
          }
        });
    }

    if (method === "get") {
      //   console.log(document.cookie)
      axios
        .get(URL, { withCredentials: true })
        .then(function (e) {
          callBack(e.data);
        })

        .catch(function (error) {
          if (error.response) {
            // The request was made and the server responded with a status code
            // that falls out of the range of 2xx
            console.log(error.response.data);
            console.log(error.response.status);
            console.log(error.response.headers);
            if (
              error.response.status === 401 ||
              error.response.status === 419
            ) {
              console.log("Unauthorized");
              let obj = {
                code: error.response.status,
                message: "Unauthorized",
              };
              callBack(obj);
              router.push("/login");
            }
          } else if (error.request) {
            // The request was made but no response was received
            // `error.request` is an instance of XMLHttpRequest in the browser
            // and an instance of http.ClientRequest in node.js
            console.log(error.request);
          } else {
            // Something happened in setting up the request that triggered an Error
            console.log("Error", error.message);
          }
        });
    }
  },
};

export default NetworkManager;

I have implemented when the token is expires on the next api call it routes to the login page. I need to implement this as to riderect to the dashboard when the cookie has an active session. Thank you all for your time, and I genuinely appreciate any help or suggestions you can offer.

Nuxt3 dynamic

can someone help me with creating a dynamic component based on JSON data in NUXT3.

I have DataTable body component like this:

<tbody class="divide-y divide-gray-200">
          <tr v-for="item in data" :key="item._id">
            <td v-for="column in columns" class="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
              <div v-if="column.definition">
                <component :is="resolveComponent(column?.definition(item[column.key]).component)" v-bind="column?.definition(item[column.key]).component.props" >
                  {{ column?.definition(item[column.key]).slot }}
                </component>
              </div>
              <div v-else>{{ item[column.key] }}</div>
            </td>
          </tr>
        </tbody>

As you can see I want to render a component, where the :is prop is defined in column?.definition(item[column.key]).component

The definition function return an object and the .component property contains a simple string, as you can see here
{title: 'Email', key: 'email', definition: (item)=>{return {component: 'GeneralButton', props: {to: item._id}, slot: item}}}

So the result in this exmaple, which should be rendered is actualy:

<component :is="resolveComponent('GeneralButton')" ... >

And thats the problem, the resolveComponent doesnt work while I pass a variable in it. In case I pass there directly the same string, which is returned by definition function it works great.

I tried some other options, but none of them worked. The most used one is to use a global component, so the GeneralButton should be global. This aproach works, but I want to create a fully customisable component and I actualy dont know, which component will I want to use in future so this is not a good solution for me. (I saw also an advice to set all components as global and I want to avoid this cause of performance issues).

Other aproach was to override Nuxt3 auto import and manualy import desired component to DataTableBody component. This alse works and the resolveComponent() function than works with varibale :is, but it has the same problem as the previous one, I dont know which component I will get in definition() function. This should Actualy work, if there was a way to define the import dynamicly based on variable, but I am quite sure it is no possible, something like:

import {`$componentToRender`} from '#components' //This does not work and I didnt find any solution which works

Is there actualy a way to do this? Thanks 🙂

write access denied when when Deploying Firebase Functions

Suddenly failed to deploy Firebase functions,

firebase deploy --only functions

it said write access was denied, I entered code here owner account that allowed me to write, but it is not working, I have checked the billing account I don’t see any problem, i have a balance in my billing account, I already setup google cloud engine and initialize google cloud cli

There was an issue deploying your functions. Verify that your project has a Google App Engine instance setup at https://console.cloud.google.com/appengine and try again. If this issue persists, please contact support. Upload Error: HTTP Error: 403, Write access to project 'project-name' was denied: please check the billing account associated and retry

Error: HTTP Error: 403, Write access to project 'project-name' was denied: please check billing account associated and retry
[2024-04-13T07:54:21.991Z] Error Context: {
  "body": {
    "error": {
      "code": 403,
      "message": "Write access to project 'project-name' was denied: please check billing account associated and retry",
      "status": "PERMISSION_DENIED"
    }
  },
  "response": {
    "statusCode": 403
  }
}

How to draw circle or arc using d3, by points excluding radius and angle?

In fact, I succeeded to put d3 lines, d3 circles and d3 arcs with radius and angles.

but to draw objects in line with scales (x-scale / y-scale), i found that it is ambiguous to apply scale to radius of circles and arcs.

So, now I changed and I’m looking for a way to draw d3 circles or d3 arcs by using points. The points can be calculated by using radius * cos / sin, and then the points could be scaled.

I made a path function like below

function d3_path( apts ){

    var sPath;
    
    sPath = "";

    sPath = "M " + apts[0]['x'] + " " + apts[0]['y'] + " C ";

    for( var i = 1 ;  i < apts.length ; i++) {

        sPath += apts[i]['x'] + " " + apts[i]['y'] ;

    }        

    return sPath

}

and then tried to draw circle and arc like below

ARC

            var vertex = [];

            for( var j = 0; j < dataGroup[i].values.length; j++ ){
                var iposi = vertex.length;
                vertex[iposi] = [];
                vertex[iposi]['x'] = xscale( dataGroup[i].values[j].x );
                vertex[iposi]['y'] = yscale( dataGroup[i].values[j].y );
            }

            og.select("#layer" + dataGroup[i].values[0].layer )
            .append('svg:path') 
            .attr("id", dataGroup[i].values[0].name )               
            .attr('d', d3_path( vertex ) )  
            .attr('stroke-width', dwidth_out + 'px') 
            .attr('fill', 'none');

CIRCLE

          var vertex = [];

            for( var j = 0; j < dataGroup[i].values.length; j++ ){
                var iposi = vertex.length;
                vertex[iposi] = [];
                vertex[iposi]['x'] = xscale( dataGroup[i].values[j].x );
                vertex[iposi]['y'] = yscale( dataGroup[i].values[j].y );
            }

            og.select("#layer" + dataGroup[i].values[0].layer )
            .append('svg:path') 
            .attr("id", dataGroup[i].values[0].name )               
            .attr('d', d3_path( vertex ) + " Z" )  
            .attr('stroke-width', dwidth_out + 'px') 
            .attr('fill', 'none');

but the circles and arcs are shown incorrectly.

Please give some comments.

How to document function parameters’ order in JSDoc?

I’ve got a function that uses the arguments object to accept parameters, like this:

function DoLog() {
    let level='info', content, logger='log';
    switch (arguments.length) {
        case 1:
            content = arguments[0];
            break;
        case 2:
            level = arguments[0];
            content = arguments[1];
            break;
        case 3:
            level = arguments[0];
            content = arguments[1];
            logger = arguments[2];
    }
    console[logger](`[${level}] ${content}`);
}

and I want to document it in JSDoc.

I could just write:

/**
 * logger with log level and logger function specified
 * @param {String=} [level=info] - level of this log
 * @param {String} [content] - log content
 * @param {String=} [logger=log] - function to log (in console[logger])
 */

But actually there is a certain order of these three parameters, which means that I can call this function in three different ways:

  • DoLog(content)
  • DoLog(level, content)
  • DoLog(level, content, logger)

How can I document that?

After searching the web I found How do I document functions that have multiple parameter order options in JsDoc? and the answer in it says

You can use the @also tag to provide multiple method signatures

However, I didn’t find @also tag in JSDoc documentation, so it seems like an outdated answer. Therefore, I didn’t find anything helpful.

Adapting Excel Add In to Google Sheets

In our company, we have Excel add-ins for financial modeling that were created using node.js and yeoman for starting the project. The library that was used to build all the functionality though is OfficeJS. It’s a library that allows an add-in to work on Excel desktop, web, or Mac with the same code.

Now we are trying to adapt these Excel add-ins for Google Sheets.What are some considerations/explorations that we need to do or requirements for implementing the excel add-ins to google sheets so that it becomes a google add-in

Nodemon not running: “[nodemon] clean exit – waiting for changes before restart”

I have been following an online tutorial, I have verified my code with the tutorial but still not able to resolve the error. I have attached my code for reference. Please help!!!

Index.js

import app from "./server.js";
import mongodb from "mongodb";
import dotenv from "dotenv";

async function main(){
    dotenv.config();
    const client = new mongodb.MongoClient(process.env.MOVIEREVIEWS_DB_URI);
    const port = process.env.PORT || 8000;
    try{
        // connect to mongodb cluster
        await client.connect();
        app.listen(port,()=>{
            console.log("server is running on port:"+port);
        });
    }
    catch(e){
        console.error(e); 
        process.exit(1);
    }
    main().catch(console.error);
}

Server.js

import express from 'express';
import cors from 'cors';
import movies from './api/movies.route.js';

const app = express();

app.use(cors()); 
app.use(express.json());
app.use("/api/v1/movies", movies);
app.use('*', (req,res)=>{
    res.status(404).json({error: "not found"});
});

export default app;

api/movies.route.js

import express from 'express';
const router = express.Router(); 
// get access to express router 
router.route('/').get((req,res) => {res.send('hello world')}); 
export default router;

How to Use AND Operator with OR Condition in Supabase Query?

I’m working on a query in Supabase where I need to select specific columns from a table based on multiple conditions. Specifically, I need to select columns a, b, and c from a table where column e is equal to a specific value (e = e) and at least one of the columns (a, b, or c) is equal to another value. Let’s call it g.

SELECT a,b,c

FROM table

WHERE e = e

AND (a = g OR b = g OR c = g);

I’m hoping for something similar to the below:

supabase
    .from('table')
    .select('a, b, c')
    .eq('e', e)
    .then(({ data, error }) => {
        if (error) {
            console.error('Error fetching data:', error.message);
        } else {
            console.log('Data:', data);
        }
    });

But additionally with the AND operator query above.

However, this only handles the condition where e = e. How can I incorporate the additional condition where at least one of a, b, or c is equal to g using the AND operator in Supabase?

I’ve tried using the .or() method within the .eq() method, but I haven’t been successful. Can anyone guide me on how to structure this query properly?

Thank you.

Cannot check index of a certain string in a PDF using Node

I am attempting to make a Node js program to read a bank statement PDF and detect the dates (Dates are on their own lines and have a ‘/’ in the third position in each string).

This is my code so far:

import {PdfReader} from "pdfreader";
import { convertArrayToCSV } from "convert-array-to-csv";

new PdfReader().parseFileItems("600067301-2024-04-03.pdf",(err,item) => {
    if (err){
        console.warn("error: err"); 
    }
    else if (!item){
        console.warn("end of file");  
    }
    else if (item.text[2] === '/'){
        console.log('date found!!!'); 
    }
})

This is the error I’m getting:

TypeError: Cannot read properties of undefined (reading ‘2’)
at file:///Users/Zayan/index.mjs:11:23
at PdfReader.parseFileItems (file:///Users/Zayan/node_modules/pdfreader/PdfReader.js:49:3)

The weird thing is that I am able to console.log (item.text[2] === ‘/’) which does return True for the date lines, however it doesn’t work for the else if statement.

Unable to correctly decrypt message in JavaScript using CryptoJS

I’m trying to create an end-to-end encrypted chat app in JavaScript using the CryptoJS library. The problem I’m having is that I can’t properly decrypt the encrypted message from the server. I have ensured that the key and IV are generated and shared correctly, but still cannot decrypt the message.

I’ve tried a few different things, including adjusting the encoding and trying different decryption options, with no success.

Here is my code snippet:

// receive encrypted message and add the message to the message box
    socket.on("receive", (msg, color="black") => {
        let [user, content] = msg.split(": ");
        let encryptedHexStr = CryptoJS.enc.Hex.parse(content);
        let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
        let decrypt = CryptoJS.AES.decrypt(srcs, sharedSecretKey,{ iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
        let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
        add_message(user + ": " + decryptedStr, color);
        console.log(decryptedStr);
    });

    // we'll send the message to the server by emitting a "send" event
    function send() {
        let message = $("#message").val();
        $("#message").val("");
        let srcs = CryptoJS.enc.Utf8.parse(message);
        let encrypted = CryptoJS.AES.encrypt(srcs, sharedSecretKey, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }).ciphertext.toString();
        socket.emit("send", username, encrypted, room_id);  
    } 

Here, sharedSecretKey and iv are correctly generated and shared in a python file.

sharedSecretKey = get_random_bytes(16)
iv = get_random_bytes(16)

@socketio.on("distributeAES")
def distributeAES(room_id):
    if room_id in key:
        sharedSecretKey = key[room_id]["sharedSecretKey"]
        return sharedSecretKey
    else:
        return {"error": "Room ID not found or key not available"}
    
@socketio.on("distributeIV")
def distributeIV(room_id):
    if room_id in key:
        iv = key[room_id]["iv"]
        return iv
    else:
        return {"error": "Room ID not found or IV not available"}
    

However, when I try to decrypt the message from the server, the decrypted result is empty.
enter image description here
enter image description here

I suspect the problem may be in the decryption process, but I’m not sure what’s going wrong. I’m hoping to find a correct way to decrypt the message and display it in the message box.

If anyone could provide some help or point out any mistakes I might be making, I’d be very grateful. Thanks!