Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable } from '@angular/core';
- import { Router } from '@angular/router';
- import { Storage } from '@ionic/storage';
- import { ToastController, Platform } from '@ionic/angular';
- import { BehaviorSubject } from 'rxjs';
- @Injectable()
- export class AuthenticationService {
- authState = new BehaviorSubject(false);
- public token : string;
- constructor(
- private router: Router,
- private storage: Storage,
- private platform: Platform,
- public toastController: ToastController
- ){
- this.ifLoggedIn();
- }
- async ifLoggedIn() {
- await this.storage.get('token').then((token) => {
- if(token){
- this.authState.next(true);
- this.token = token;
- }
- });
- }
- login(){
- this.storage.set('token', 'asd123asdasd12354151asd').then((response) => {
- this.router.navigate(['app/inicio']);
- this.authState.next(true);
- });
- }
- logout(){
- this.storage.remove('token').then(() => {
- this.router.navigate(['app/inicio']);
- this.authState.next(false);
- });
- }
- isAuthenticated(){
- return this.authState.value;
- }
- getToken(){
- return this.token;
- }
- }
- import { Component } from '@angular/core';
- import { Router } from '@angular/router';
- import { Events, MenuController, Platform } from '@ionic/angular';
- import { SplashScreen } from '@ionic-native/splash-screen/ngx';
- import { StatusBar } from '@ionic-native/status-bar/ngx';
- import { AuthenticationService } from './authentication.service';
- @Component({
- selector: 'app-root',
- templateUrl: 'app.component.html',
- styleUrls: [
- './side-menu/styles/side-menu.scss',
- './side-menu/styles/side-menu.shell.scss',
- './side-menu/styles/side-menu.responsive.scss'
- ]
- })
- export class AppComponent {
- isAuth : boolean;
- constructor(
- public auth : AuthenticationService,
- private events: Events,
- private menu: MenuController,
- private platform: Platform,
- private splashScreen: SplashScreen,
- private statusBar: StatusBar,
- private router: Router,
- ) {
- this.initializeApp();
- }
- initializeApp() {
- this.platform.ready().then(() => {
- this.statusBar.styleDefault();
- this.splashScreen.hide();
- this.isAuthenticated();
- });
- //this.isAuthenticated();
- }
- isAuthenticated(){
- console.log(this.auth.getToken()); // devuelve un "undefined"
- console.log(this.auth.token); // devuelve un "undefined"
- console.log(this.auth); // y este es el más curioso devuelve el objeto auth y dentro del objeto se ve seteado el token y no puedo acceder a el de las formas anteriormente dichas.....
- }
- logOut(){
- this.auth.logout();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement