0

In my Angular project I want to implement deleting items but when I use this.currentClient.id or .this.currentClient.name i get this error:

Type error: Object is possibly 'null'

This is a fragment with updating currentClient data and deleting function:

export class ClientDetailsComponent implements OnInit {
  currentClient = null;
  message = '';

getClient(id: string | null): void {
    this.clientService.get(id)
      .subscribe(
        data => {
          this.currentClient = data;
          console.log(data);
        },
        error => {
          console.log(error);
        });
  }

  deleteClient(): void {
    this.clientService.delete(this.currentClient.id)
      .subscribe(
        response => {
          console.log(response);
          this.router.navigate(['/clients']);
        },
        error => {
          console.log(error);
        });
      }

I can't find out why it can be null :(

caramel
  • 60
  • 8
  • 1
    Because you’re initializing it with a null value? `currentClient = null`. Perform a null value check before accessing the sub properties, or use optional chaining, ie `this.currentClient?.id` – Terry Jul 04 '21 at 21:27

1 Answers1

0

Your editor is right, and I also believe that this object can be null. Why? Because of this line:

currentClient = null;

From an outside point of view, I can call the delete function at any time, meaning that your currentClient variable can actuaby null because you initialize it as such!

There are two main options for you to solve this:

The second solution should be used ONLY IF you know that your variable will never be null or undefined once you exit the constructor of your class.

You might also want to have a look at the nullable operator. private currentClient?: Client;

Paul Evans
  • 434
  • 2
  • 13