Home > Software design >  Angular project working on localhost but not on GitHub Pages
Angular project working on localhost but not on GitHub Pages

Time:07-08

I am making a todo list in Angular that also saves and restores on refresh, and on localhost I can add to the list and the item displays below the add button. On GitHub Pages, when I click add it does nothing.

GitHub Repo

GitHub Pages

This is the error I am getting from the console:

ERROR TypeError: Cannot read properties of null (reading 'push')
    at e.addTodo (main.2beb7ccacdd609b1.js:1:139904)
    at main.2beb7ccacdd609b1.js:1:140617
    at Qh (main.2beb7ccacdd609b1.js:1:60440)
    at i (main.2beb7ccacdd609b1.js:1:60625)
    at HTMLFormElement.<anonymous> (main.2beb7ccacdd609b1.js:1:107043)
    at v.invokeTask (polyfills.a66b249bad4eb06b.js:1:7168)
    at Object.onInvokeTask (main.2beb7ccacdd609b1.js:1:82284)
    at v.invokeTask (polyfills.a66b249bad4eb06b.js:1:7089)
    at M.runTask (polyfills.a66b249bad4eb06b.js:1:2563)
    at m.invokeTask [as invoke] (polyfills.a66b249bad4eb06b.js:1:8219)

CodePudding user response:

The Problem

The problem is not from GitHub Pages. It is from the Angular code itself.

The code works well except for one thing. On a first-time visit of the Angular application in a browser, the todos key has never been set before in localStorage in that domain (GitHub Pages or localhost). So the getTodos() function returns null thus making the this.todos initializing statement in ngOnInit() to be set to null.

Solution

To solve the problem, add the if-null operator (??) to the return of getTodos() to include an empty array ([]). That way, if it is a first-time visit, or if the user played around and cleared localStorage, the app should still work (given that new todos will be pushed to an empty array).

So change line 59 of todos.component.ts from

return JSON.parse(localStorage.getItem("todos")!);

to

return JSON.parse(localStorage.getItem("todos")!) ?? [];
  • Related