0

This is the exact error: Type 'string | null' is not assignable to type 'string'. Type 'null' is not assignable to type 'string'.ts(2322) (property) NavbarComponent.loggedInUser: string

Here is my code:

/* navbar-component-ts */
import { Component, OnInit } from '@angular/core';

import { AuthService } from 'src/app/services/auth.service';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'flash-messages-angular';
import { Client } from '../../models/Client';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
/* Properties */
isLoggedIn!: boolean;
loggedInUser!: string;
showRegister!: boolean;


  constructor(
    private authService: AuthService,
    private router: Router,
    private flashMessage: FlashMessagesService
  ) { }

  ngOnInit() {
    this.authService.getAuth().subscribe(auth => {
      if(auth) { 
        this.isLoggedIn = true;
        this.loggedInUser = auth.email;
      }else {
        this.isLoggedIn= false;
      }
    })
  }
}
1
  • 1
    Please consider modifying the code in this question so as to constitute a minimal reproducible example which, when dropped into a standalone IDE like The TypeScript Playground (link), clearly demonstrates the issue you are facing. This will allow those who want to help you to immediately get to work solving the problem without first needing to re-create it. And it will make it so that any answer you get is testable against a well-defined use case. Commented Jul 24, 2021 at 20:57

2 Answers 2

1

The declaration for you loggedInUser is fine.

I think the problem comes from auth.email, try this:

ngOnInit(): void {
    this.authService.getAuth().subscribe(auth => {
        if (auth) {
            this.isLoggedIn = true;
            const userLoggedIn = auth?.email;
            this.loggedInUser = userLoggedIn || 'no-email';
        } else {
            this.isLoggedIn = false;
        }
    });
}

I believe the property email from your auth object can be string or null, if it is null, then, as the error message says, the value null is not assignable to a variable type of string

Also, you can do this as well, although, personally, I don't use it

 loggedInUser!: string | null;

loggedInUser can hold string and null values.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I've been trying so hard all day to figure it out and thanks for the tip too! loggedInUser!: string | null;
1

just modify declartion

loggedInUser!: string;

to be

loggedInUser: string;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.