Search code examples
javascripthtmlangulargetrender

HTML seems to be trying to render a variable before it's initialized in Angular


The application works fine, but the console seems to display this error every alternate time I refresh:

GET http://localhost:4200/[object%20Object] 404 (Not Found) @ lists.component.html:3 (seems to reference 3rd line of html code below)

I reckon that HTML is trying to render the l.image variable before it's properly initialized via a GET request from a local SQL?

My application essentially uses Angular to query a node JS server, which returns an SQL query result. Thank you in advance.

Angular Code

export class ListsComponent implements OnInit {

  lists:any

  constructor(private http: HttpClient, private router: Router, private cloud: Cloud, private sanitizer: DomSanitizer) {
    this.getImages()
   }

  ngOnInit() {
  }

  async getImages(){
    this.lists = await this.http.get<any>('/lists').toPromise()
  }

Node JS code

app.get('/lists', async (req, resp) => {
    const conn = await pool.getConnection()
    try {
        const [ result, _ ] = await conn.query(SQL_SELECT_ALL_FROM_LISTS)

        resp.status(200)
        resp.type('application/json').send(result)
    } catch(e) {
        console.error('ERROR: ', e)
        resp.status(500)
        resp.end()
    } finally {
        conn.release()
    }
})

HTML

    <li *ngFor = "let l of lists" class="list-group-item d-flex justify-content-between align-items-center">

        <img *ngIf = "l.image !== 'undefined'" [src]="l.image" class="img-thumbnail img-fluid" width="10%">
        
        <a (click) = "routeToTasks(l.listID, l.listName)" class="list-group-item list-group-item-action list-group-item-primary">{{l.listName}}</a>
        <button type="button" class="btn btn-danger" (click)="deleteList(l.listID)">Delete</button>    
    </li>

Solution

  • Try using question mark just before using the dot operator as is shown below:

    <li *ngFor = "let l of lists" class="list-group-item d-flex justify-content-between align-items-center">
        <img *ngIf = "l?.image !== 'undefined'" [src]="l?.image" class="img-thumbnail img-fluid" width="10%">
        <a (click) = "routeToTasks(l.listID, l.listName)" class="list-group-item list-group-item-action list-group-item-primary">{{l.listName}}</a>
        <button type="button" class="btn btn-danger" (click)="deleteList(l.listID)">Delete</button>    
    </li>