'Why Is My Interpolation No Longer Working

Hello I'm doing a login and registration for a application that I'm developing which is functioning the way it should with the api, my issue is at that the first name was showing once the I logged on but once. Once I did a log out now it no longer works and I can't figure out why.

I now get an error saying Cannot read properties of undefined(reading firstName) I added a ( elvis) to stop the error. I did a logout because when a new user logged in it was showing the previous user which was another issue I need to work on. Can someone please point me in the right direction. In my login function its set item to local storage. I figured if I delete it and logged in again it would reset in local storage even if I deleted it. I have included relevant snippet of code.

account.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { environment } from '@environments/environment';
import { User } from 'src/app/_models';

@Injectable({ providedIn: 'root' })
export class AccountService {
    private userSubject: BehaviorSubject<User>;
    public user: Observable<User>;

    constructor(
        private router: Router,
        private http: HttpClient
    )
     {
        this.userSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('user')));
        this.user = this.userSubject.asObservable();
    }

    apiUrl = '/users'

    public get userValue(): User {
        return this.userSubject.value;
    }

    login(username, password, email) {
        return this.http.post<User>(`${environment.apiUrl}/authenticate`, { username, password, email })
            .pipe(map(user => {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('user', JSON.stringify(user));
                this.userSubject.next(user);
                console.log("Trying to get firstName", user.firstName)
                return user;
            }));
    }

    logout() {
        // remove user from local storage and set current user to null
        localStorage.removeItem('user');
        this.userSubject.next(null);
        this.router.navigate(['/account/login']);
    }

    register(user: User) {
        return this.http.post(`${environment.apiUrl}/register`, user);
        //return this.http.post(`${environment.baseUrl}/users/register`, user);
        
    }

    forgotPassword(email: string) {
        return this.http.post(`${environment.apiUrl}/forgot-password`, { email });
    }

    validateResetToken(token: string) {
        return this.http.post(`${environment.apiUrl}/validate-reset-token`, { token });
    }
    
    resetPassword(token: string, password: string, confirmPassword: string) {
        return this.http.post(`${environment.apiUrl}/reset-password`, { token, password, confirmPassword });
    }

    verifyEmail(token: string) {
        return this.http.post(`${environment.apiUrl}/verify-email`, { token });
    }

    getAll() {
        return this.http.get<User[]>(`${environment.apiUrl}/users`);
    }

    getById(id: string) {
        return this.http.get<User>(`${environment.apiUrl}/users/${id}`);
    }

    update(id, params) {
        return this.http.put(`${environment.apiUrl}/users/${id}`, params)
            .pipe(map(x => {
                // update stored user if the logged in user updated their own record
                if (id == this.userValue.id) {
                    // update local storage
                    const user = { ...this.userValue, ...params };
                    localStorage.setItem('user', JSON.stringify(user));

                    // publish updated user to subscribers
                    this.userSubject.next(user);
                }
                return x;
            }));
    }

    delete(id: string) {
        return this.http.delete(`${environment.apiUrl}/users/${id}`)
            .pipe(map(x => {
                // auto logout if the logged in user deleted their own record
                if (id == this.userValue.id) {
                    this.logout();
                }
                return x;
            }));
    }
}

auth.service

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Router } from '@angular/router';



const AUTH_API = 'http://localhost:4100/users/auth/';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor(private http: HttpClient) { }

  login(credentials): Observable<any> {
    return this.http.post(AUTH_API + 'signin', {
      username: credentials.username,
      
      password: credentials.password
    }, httpOptions);
  }

  register(user): Observable<any> {
    return this.http.post(AUTH_API + 'signup', {
      username: user.username,
      email: user.email,
      password: user.password
    }, httpOptions);
  }

  
}

html

                <h1 class="float-right" style="font-size: 10px;">{{user.firstName}}</h1>
              
                
           
           <div class="dropdown-menu dropdown-menu-right" style="width: 25px; margin-left: -30px" aria-labelledby="navbarDropdown">
            <a class="dropdown-item" href="#">Profile</a>
            <a class="dropdown-item" routerLink="">Logout</a>
            <a class="dropdown-item" routerLink="wishlistlist">Favorites</a>
            <a class="dropdown-item" href="#">Option D</a>
        </div>

header.component.ts

import { Component, Input, OnInit, Query } from '@angular/core';
import { CartService } from 'src/app/services/cart.service';
import { CartItem } from 'src/app/models/cart-item';
import { Product } from 'src/app/models/product';
import {ProductService} from 'src/app/services/product.service';
import { ProductListComponent } from '../../shopping-cart/product-list/product-list.component';
import { MessengerService } from 'src/app/services/messenger.service';
import { wishlistUrl } from 'src/app/config/api';
import {NgbModal, ModalDismissReasons, NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { SearchService, Products} from '@app/services/search.service';
import { User } from '@app/_models/user';
import { AccountService } from '@app/_services';
import { SearchComponent } from '../search/search.component';
import { BehaviorSubject, Observable } from 'rxjs';
import { AuthService } from '@app/services/auth.service';


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

export class HeaderComponent  {


   user: User;

   userSubject: BehaviorSubject<User>;

  result;

 // implements OnInit
  constructor( private msg: MessengerService, private cartService:CartService,private accountService: AccountService,private modalService: NgbModal,
               private productService: ProductService, private searchService:SearchService, private auth:AuthService)

   { 
    
  }
  ngOnInit(): void {

    }

logout(){
  localStorage.removeItem('user');
  this.userSubject.next(null);
  console.log("Removing user from local storage")
  //this.router.navigate(['/account/login']);

 }
}

Thanking You In Advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source