[英]ERROR TypeError: _co.getAdmin is not a function
這是一個Angular應用程序,它的getAdmin()
函數getAdmin()
有auth.service
,但我不知道是什么。 當我將此函數移至app.component.ts
並更改為 HTML 中的"getAdmin()"
時,沒問題,但我需要在服務中使用此函數。 請告訴我出了什么問題,我該如何解決。
附注。 變量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>
最好不要從 html 調用在 service 中編寫的函數。 我認為,您可以通過將服務范圍從私有更改為公共來解決當前的問題。 但最好的方法是從 html 調用組件內部的函數,並從該函數調用內部服務的getAdmin() 。 最佳實踐是在進行依賴注入時將服務范圍保持為私有。
應用程序組件.html
<a class="nav-link" *ngIf="adminExists()" routerLink="/admin" routerLinkActive="active">Admin</a>
應用服務.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) {
}
adminExists(){
return _authService.getAdmin();
}
}
在 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(public _authService: AuthService) {
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.