2017-06-12 26 views
1

什麼在我的腦海:如何將模型函數放置在單獨的文件中以便能夠從任何組件(而不是userIsAdmin(用戶))執行類似user.isAdmin()的操作?

User.ts

export interface User 
{ 
    id: number; 
    name: string; 
    email: string; 
    level: number; 
} 

home.component.ts

import { User } from 'models/User'; 

@Component({ selector: 'app-home', 
      templateUrl: './home.component.html')} 

export class HomeComponent { 

user: User; 

constructor() {} 

userIsAdmin(user: User) 
{ 
    return user.level === 1 
} 

home.component.html

<i class="delete" *ngIf="userIsAdmin(user)"></i> 

使用這種方法,我的家將會填充太多與模型相關的功能,我需要在所有組件中單獨定義。我可以將所有功能放在一個服務中,並將它們注入到所有組件中,但我仍然無法執行user.isAdmin()。我該怎麼做?

回答

1

也許是裝飾者?

function isAdmin(construct) { 
    construct.prototype.isAdmin = function() { 

     return this.roles.includes('admin'); 
    } 
} 

@isAdmin 
class User { 
    roles: string[] = ['admin']; 
} 



console.log('isAdmin?', (new User).isAdmin()) 
+0

這是多一點的工作是個好主意。謝謝。 – anonym

1

存儲isAdmin創建AuthService,並在每個組件 注入當u需要。

AuthService

@Injectable() 
export class AuthService { 
private isAdmin: boolean; 

    get isAdmin(): boolean { 
     return this.isAdmin; 
    } 
    setIsAdmin(level: boolean): void{ 
     this.isAdmin = level 
    } 
} 

當你得到用戶當時設定的用戶是管理員或不使用setIsAdmin方法

// write this function in that service when you get user. 

,如:this.authService.setAdmin(user.level===1?true:false);

//組件

export class UserComponent{ 
    constructor(public auth: AuthService){} 
} 

您可以在HTML this.auth.isAdmin訪問。

例如<i class="delete" *ngIf="this.auth.isAdmin"></i>

也可以創建可變成部件,並用它。

//寫入onNgInit()方法 this.isAdmin = this.auth.isAdmin;

例如<i class="delete" *ngIf="isAdmin"></i>

+0

更多信息。謝謝。 – anonym

相關問題