Search code examples
javascriptarraysangularsortingngoninit

Reference Error inside ngOnInit


I am receiving an error on in my console that says ERROR ReferenceError: sortedArr is not defined after I have defined it and sorted it.

Here is my app.component.ts file:

import { Component } from '@angular/core';
import { HttpClient, OnInit } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {
  title = 'Contacts';
  contacts: any[] = this.contacts;

  constructor (private httpClient: HttpClient) {}

  ngOnInit(): void {
      //Pull JSON data from REST API
    this.httpClient.get('***URL TO JSON DATA***')
    .subscribe((data) => {
        this.contacts = data;

        //Sort JSON object
        let arr = this.contacts;
        let sortedArr = arr.sort( (a, b) => {
          return (typeof a.name === 'string') - (typeof b.name === 'string') || a.name - b.name || a.name.localeCompare(b.name);
          }););
        console.log(sortedArr);
    });
  }

The sorted array of objects is being bound to my HTML on my page in my web app, but it isn't in the console. Why would I be getting a ReferenceError when I have just defined AND sorted this array?

The real reason I am asking is because I need to do some different things to this array of objects to have it behave with my HTML correctly. It has allowed me to sort it via the function I wrote, but I cannot call another method on the sortedArray variable because its saying it isn't defined.


Solution

  • you are importing OnInit from the wrong library

    import { HttpClient } from '@angular/common/http';
    

    change it to:

    import { Component, OnInit } from '@angular/core';
    

    Typo: );--> remove this and it will work let keyword limits the variable scope to the block and because of typo ); you are not able to access it outside the scope of the block.

    ngOnInit(): void {
          //Pull JSON data from REST API
        this.httpClient.get('***URL TO JSON DATA***')
        .subscribe((data) => {
            this.contacts = data;
    
            //Sort JSON object
            let arr = this.contacts;
            let sortedArr = arr.sort( (a, b) => {
              return (typeof a.name === 'string') - (typeof b.name === 'string') || a.name - b.name || a.name.localeCompare(b.name);
              }););--> remove it
            console.log(sortedArr);
        });
      }