Angular 2+ - After successful Login, change my Login component in Header to User Account Component

Viewed 3162

I am building an Angular2+ App. Started learning angular 1 week back.

Following is the structure -index.html - AppComponent(app-root) - Header Component(header) - Signup Component(signup)

SignupComponent is a Modal.

After a successful login, I want to replace my Signup Account with User Component(which should be drop down menu with multiple links - (Account link, Logout link) ).

The solution which I thought was that on a successful login, I should emit the event to Header component from Signup Component.

On receiving the event , Header component should switch to UserComponent and hide the Signup Component Div.

User Component should have a Auth Gaurd because the links in drop down should be protected.

I have few questions

  • How should I route from Signup Modal to index.html with changes needed? - Do I need to refresh the index.html where it will load the account component? How should I route to index.html which should have the new User component in place of signup component. ?

  • Is this a right approach? If not,what is the ideal way to do this in angular 2+?

2 Answers

I am writing these tips for angular 4.3. Firstly i will suggest not to put your html into index.html file, its not a right approach. APP component is the main component where you can put all html there. Now except the header (login/logout links should be here) and footer remove other html and use router-outlet to build a single page application.

I suppose you already have a login/SignIn component and a login/SignIn service. Firstly set a variable in login service and mark it false in constructor. Now you need to change value of this variable on login and logout operation.

After that need to call login service into app component and initialize it in constructor.

Finally in app component html where you have login/logout links, use ngIf to show/hide those links with login service variable.

My code is something like below.

Login Service

export class LoginService{
    isloggedin : boolean;
    constructor(private _http: Http){
        this.isloggedin = false;
    }

App Component HTML

<li *ngIf="!loginService.isloggedin"> <a routerLink="login">Login</a> </li>
<li *ngIf="!loginService.isloggedin"> <a routerLink="register">Register</a> </li>
<li *ngIf="loginService.isloggedin"> <a routerLink="logout">Logout</a> </li>

App Component

import { LoginService } from './login.service';

export class AppComponent {
constructor(private loginService: LoginService){
}

After logout i simply clear localstorage and set isloggedin to false;

Related