K
K
kikosko2018-10-17 14:35:59
JavaScript
kikosko, 2018-10-17 14:35:59

How to remember the value of a variable after page reload?

I want to remember the value of the loggedIn variable after reloading the page, because the call to the corresponding function and button style in appComponent.html depends on its value. Please tell me how to implement it?
AppComponent.html

<li class="nav-item">
                <a class="btn btn-outline-success"
                   [class.btn-outline-success]="!this.loggedInService.loggedIn"
                   [class.btn-outline-danger]="this.loggedInService.loggedIn"
                   (click)="this.loggedInService.loggedIn ? logout() : logIn()">
                    {{this.loggedInService.loggedIn? 'Exit' : 'Enter'}}
                </a>
            </li>

AppComponent.ts
export class AppComponent implements OnInit {
    constructor(private loggedInService: LoggedinService,
                private router: Router) {
    }

    ngOnInit() {
    }

    logIn(): void {
        this.loggedInService.login();
        if (this.loggedInService.loggedIn) {
            let redirect = this.loggedInService.redirectUrl ? this.loggedInService.redirectUrl :
                '/gallery';
            this.router.navigate([redirect]);
        }
    }

    logout(): void {
        this.loggedInService.logout();
        this.router.navigate(['/']);
    }
}

LoggedInService :
export class LoggedinService implements OnInit {
    redirectUrl: string;
    loggedIn: boolean = false;
    constructor() {}

    ngOnInit(): void  {}

    login(): boolean {
        localStorage.setItem('login', 'true');
        return this.loggedIn = true;
    }

    logout(): boolean {
        localStorage.removeItem('login');
        return this.loggedIn = false;
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Eremin, 2018-10-17
@kikosko

localStorage.setItem("isLoggedIn", loggedIn)

инициализация переменной
loggedIn: boolean = (localStorage.getItem("isLoggedIn") === 'true') || false

but you already have it, what is
the difficulty then?

K
Karpion, 2018-10-17
@Karpion

The answer depends a lot on why you need it. As a variant - to write down in cookie.
However, suppose the user has several windows open with this page - then it is not clear how to distinguish these variables from different pages.
There are still different options for reloading the page - for example, going somewhere to another page (including to another site) and returning back.
This is not an answer, but only an indication of possible difficulties.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question