【发布时间】:2020-06-05 09:56:38
【问题描述】:
这是一个Angular 应用程序,auth.service 中的函数getAdmin() 有问题,但我不知道是什么问题。当我将这个函数移动到app.component.ts 并在HTML 中更改为"getAdmin()" 时,没问题,但我需要这个函数在服务中。请告诉我出了什么问题,我该如何解决。
PS。变量 admin 以字符串形式返回 'true' 或 'false'。
它是带有用户身份验证、令牌的电子商务应用程序,现在我尝试添加管理员。
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 {
constructor(private http: HttpClient, private _router: Router) { }
getAdmin() {
if (localStorage.getItem('admin') === 'true') return true;
return false;
}
}
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 {
constructor(private _authService: AuthService) {
}
}
app.component.html:
<a class="nav-link" *ngIf="_authService.getAdmin()" routerLink="/admin" routerLinkActive="active">Admin</a>
【问题讨论】:
-
在这一行中:
if (localStorage.getItem('admin') === 'true') return true;您是否正在检查布尔值true(无引号)?或字符串'true'(引号)。您有引号,因此您将字符串与localStorage.getItem('admin')进行比较。您可以查看localStorage.getItem('admin')是布尔值还是字符串或其他:console.log(typeof localStorage.getItem('admin')); -
我检查了它 - 当 'admin' 为空时,它返回对象 (null),如果不是 - 返回字符串 'true' 或 'false'。它可以正常工作,但感谢您的回复。
标签: html angular typescript service typeerror