gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'loggedIn' of undefined

转载 作者:行者123 更新时间:2023-12-02 23:07:22 24 4
gpt4 key购买 nike

我正在尝试创建一个导航栏,当用户已经登录时显示注销,反之亦然。但按钮已完全停止显示。

这让我很烦恼。我不知道我哪里错了。

我添加了 app.component.ts 文件。

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){}
}

最佳答案

问题是您将 authService 作为私有(private)注入(inject),而模板只能访问公共(public)方法、属性。

尝试将您的组件更改为:

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) {}
}

虽然这可行,但直接从模板调用服务可能不是最好的主意。

关于javascript - 类型错误 : Cannot read property 'loggedIn' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57527645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com