I am trying to create a nav bar that shows logout when user is already logged in and vice versa. But the buttons have completely stopped showing.
This is bugging me a lot. I don't know where I am going wrong.
I added the app.component.ts file.
auth.service.ts
import { Injectable } from '@angular/core';
import{HttpClient} from '@angular/common/http';
import{Router} from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private _registerUrl="http://localhost:3000/api/register";
private _loginUrl="http://localhost:3000/api/login"
_router: Router;
constructor(private http: HttpClient) { }
registerUser(user){
return this.http.post<any>(this._registerUrl, user)
}
loginUser(user){
return this.http.post<any>(this._loginUrl, user)
}
loggedIn(){
return !!(localStorage.getItem('token'))
}
logoutUser(){
localStorage.removeItem('token')
this._router.navigate(['/home'])
}
}
app.component.html
<div class="topnav" id="myTopnav">
<a class='nav-link' routerLink='/home' routerLinkActive="active">Home</a>
<a class='nav-link' *ngIf="!_authService.loggedIn()"routerLink='/register' routerLinkActive="active">Register</a>
<a class='nav-link' *ngIf="!_authService.loggedIn()" routerLink='/login' routerLinkActive="active">Login</a>
<a class='nav-link' style ="cursor:point" *ngIf="_authService.loggedIn()" (click)="_authService.logoutUser()" >Login</a>
<a href="javascript:void(0);" class="icon" onclick="myFunction()">
<i class="fa fa-bars"></i>
</a>
</div>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<router-outlet></router-outlet>
app.component.ts
import { Component } from '@angular/core';
import{AuthService} from './auth.service'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'sams-attendance';
constructor(private _auth: AuthService){}
}
The issue is that you're injecting authService
as private and template can access only public methods, properties.
Try changing your component to:
import { Component } from '@angular/core';
import { AuthService } from './auth.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'sams-attendance';
constructor(public _auth: AuthService) {}
}
While this will work, it might be not the best idea to call service from template directly.
Your _authSerivice is undefined check have you passed _authService to templte
Instead you should directly use logedIn in templte
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.