Angular getCurrentUser different roles with different models

Discussão em 'Angular' iniciado por Zed, Novembro 13, 2024.

  1. Zed

    Zed Guest

    I have a logic issue and I’m not sure how to proceed. I have an auth method that sends email and password, and my API responds with a JWT token. Then, I need a getCurrentUser method, but I have multiple roles, each with its own model—for example, I have admin, moderator, and user, and each has its own model. How should I approach this?

    I’ve thought about having 3 methods: LoadCurrentUser, LoadCurrentModo, and LoadCurrentAdmin, each receiving its own model. I’m not sure if it’s a good approach and how I could determine which method to call after the user has authenticated. Then, I asked ChatGPT if it has any idea.

    export type UserType = Admin | Modo | User;

    getCurrentUser(): Observable<UserType> {
    return this.http.get<UserType>(`/api/user/current`).pipe(
    map((data: any) => {
    switch (data.role) {
    case 'admin':
    return data as Admin;
    case 'modo':
    return data as Modo;
    default:
    return data as User;
    }
    })
    );
    }



    Do you have an idea?

    Continue reading...

Compartilhe esta Página