How to show/hide navigation list corresponding to login

Hello Everyone!
I’m creating a simple login authentication with MEAN stack using angular 4 HTTP client in the front-end. I’m trying to implement show/hide navigation based on login. When the user login it must show the navigation-list if not hide it but my code doesn’t show any error. Below is my code please have a look and let me know where my doing wrong.

//navbar.component.html

<ul class="nav navbar-nav">
    <ng-template *ngIf="isAuthenticated()"> <!-- Here I used [ngIf]="isAuthenticated()" as well still it doesn't work-->

//navbar.component.ts

export class NavbarComponent implements OnInit {
  constructor(private authService: AuthService, 
              private router: Router) { }
  ngOnInit() {
  }
  onLogout() {
    this.authService.logout()
      .subscribe(
        (res) => {
          if (res) {
            this.router.navigate(['/login']);
          }
        }
      );
  }
  isAuthenticated() {
    this.authService.isAuthenticated();
  }
}

//Login.component.ts

export class LoginComponent implements OnInit {
  signinForm: FormGroup;
  constructor(private authService: AuthService,
              private router: Router) { }
  ngOnInit() {
    this.signinForm = new FormGroup({
      'email': new FormControl(null, [Validators.required, Validators.email]),
      'password': new FormControl(null, [Validators.required, Validators.minLength(6)])
    });
  }

  onSignin() {
    const userDetails = {
      email: this.signinForm.get('email').value,
      password: this.signinForm.get('password').value
    };

    this.authService.signInWithEmailAndPassword(userDetails)
      .subscribe(
        (res) => {
          if(res) {
            console.log('res: ', res);
            this.router.navigate(['/jobs']);
            this.authService.isAuthenticated()
              .subscribe(
                (res) => {
                  console.log('response: ', res);
                }
              );
          }
        },
        (err) => {
          alert('Invalid User Credentials');
        }
      );
    this.signinForm.reset();
  }
}

//auth.service.ts

export class AuthService {
    url = 'http://localhost:3000/api/users'
    constructor(private router: Router,
                private http: HttpClient) {}
    signInWithEmailAndPassword (userDetails) {
        return this.http.post(this.url + '/login', userDetails, { observe: 'body', responseType: 'json'})
            .map(
                (response) => {
                    return response;
                }
            )
    }

    logout() {
        return this.http.get(this.url + '/logout')
            .map((response) => {return response})
    }

    isAuthenticated() {
        return this.http.get(this.url + '/is-logged-in')
            .map((response) => { return response })
    }
}

//Back-End Code
//server.js

const userRoute = require('./routes/user-route');
app.use('/api/users', userRoute);

//user-router.js
userRoute.get('/is-logged-in', authMiddleware.isUserLoggedIn, authMiddleware.isUserActive, user.isLoggedInUser);

//auth-middleware.js

const authMiddleware = {
isUserActive: (req, res, next) => {
        req.user.isActive === true ? next() : res.status(401).send({message: 'No User Found!'});
    },
    isUserLoggedIn: (req, res, next) => {
        console.log('imcalled from auth');
        req.isAuthenticated() ? next() : res.status(401).send({message: 'You must be LoggedIn'});
    }
}

//user-controller.js

const user = {
    isLoggedInUser: (req, res) => {
        res.status(200).send(true);
    }
};

Hi @arjunkumar230223, your isAuthenticated() method of the NavbarComponent doesn’t return anything, so *ngIf="isAuthenticated()" will never be truthy… and since the HttpClient will actually return an Observable, you’ll need a slightly different approach here anyway. Try something like

<NavbarComponent>
  <div *ngIf="isAuthenticated"><!-- etc. --></div>
</NavbarComponent>
export class NavbarComponent implements OnInit {
  isAuthenticated = false

  constructor(private authService: AuthService)

  ngOnInit() {
    this.authService
      .isAuthenticated()
      .toPromise()
      .then(() => this.isAuthenticated = true)
      // Handle error response (such as 401 status)
      .catch(() => this.isAuthenticated = false)
  }
}

See the section about error handling in the docs for details.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.