Skip to main content
asdasdasdasd
Origen Enlace
nestdan
  • 1.3k
  • 1
  • 8
  • 14

Creo hay una mala detección del cambio de estado por eso no está cambiando la etiqueta o link a login cuando así debería ser. Para detección del cambio de estado de autenticación del usuario podes

podes usar BehaviorSubject teoria definido en el servicio como

Creo hay una mala detección del cambio de estado por eso no está cambiando la etiqueta o link a login cuando así debería ser. Para detección del cambio de estado de autenticación del usuario podes usar BehaviorSubject teoria definido en el servicio como

Creo hay una mala detección del cambio de estado por eso no está cambiando la etiqueta o link a login cuando así debería ser. Para detección del cambio de estado de autenticación del usuario

podes usar BehaviorSubject teoria definido en el servicio como

// services
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, map, Observable } from 'rxjs';
import { ConfigurationService } from './configuration.service';
import { Presocloud } from 'src/app/interfaces/presucloud';
import { Router } from '@angular/router';
import { HeaderComponent } from '../shared/components/header/header.component';

import { BehaviorSubject, Observable } from "rxjs";

isLoginSubject = new BehaviorSubject<boolean>(this.hasToken());

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest',
    Accept: '*/*',
  }),
};

@Injectable({
  providedIn: 'root',
})
export class AuthenticationService {
  private URL_BASE: string;

  constructor(
    private configuration: ConfigurationService,
    private http: HttpClient,
    private router: Router,
  ) {
    this.URL_BASE = this.configuration.getUrlBase();
  }

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
    }),
  };
  
  
  private hasToken() : boolean {
    return !!localStorage.getItem('token');
  }

  singup(data: any) {
    return this.http.post(this.URL_BASE + 'signup', data);
  }

  login(email: string, password: string): Observable<Presocloud> {
    const user: any = {
      email: email,
      password: password,
    };
    return this.http
      .post<Presocloud>(
        this.URL_BASE + 'login',
        JSON.stringify(user),
        this.httpOptions
      )
      .pipe(
        map((res: any) => {
          this.authSuccess(res.access_token);
          return res;
        })
      );
  }
  
  isLoggedIn() : Observable<boolean> {
 return this.isLoginSubject.asObservable();
}

  authSuccess(token: string) {
    localStorage.setItem('token', token);
     this.isLoginSubject.next(true);
  }

  getToken(): string | null {
    return localStorage.getItem("token");
  }

  logout() {
    localStorage.removeItem("token");
    this.isLoginSubject.next(false);
    this.router.navigate(["login"]);
  }

  
}
//header
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenticationService } from 'src/app/services/authentication.service';
import { Observable } from "rxjs";

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
   isLoggedIn : Observable<boolean>;

  constructor(
    private authenthication: AuthenticationService,
    private router: Router
  ) { this.isLoggedIn = authService.isLoggedIn();}

  ngOnInit(): void {}

  verifyLooged() {
this.isLoggedInO.subscribe(bole=>{if(bole ==true) this.router.navigateByUrl('home'); })
// services
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, map, Observable } from 'rxjs';
import { ConfigurationService } from './configuration.service';
import { Presocloud } from 'src/app/interfaces/presucloud';
import { Router } from '@angular/router';
import { HeaderComponent } from '../shared/components/header/header.component';

import { BehaviorSubject, Observable } from "rxjs";

isLoginSubject = new BehaviorSubject<boolean>(this.hasToken());

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest',
    Accept: '*/*',
  }),
};

@Injectable({
  providedIn: 'root',
})
export class AuthenticationService {
  private URL_BASE: string;

  constructor(
    private configuration: ConfigurationService,
    private http: HttpClient,
    private router: Router,
  ) {
    this.URL_BASE = this.configuration.getUrlBase();
  }

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
    }),
  };
  
  
  private hasToken() : boolean {
    return !!localStorage.getItem('token');
  }

  singup(data: any) {
    return this.http.post(this.URL_BASE + 'signup', data);
  }

  login(email: string, password: string): Observable<Presocloud> {
    const user: any = {
      email: email,
      password: password,
    };
    return this.http
      .post<Presocloud>(
        this.URL_BASE + 'login',
        JSON.stringify(user),
        this.httpOptions
      )
      .pipe(
        map((res: any) => {
          this.authSuccess(res.access_token);
          return res;
        })
      );
  }
  
  isLoggedIn() : Observable<boolean> {
 return this.isLoginSubject.asObservable();
}

  authSuccess(token: string) {
    localStorage.setItem('token', token);
     this.isLoginSubject.next(true);
  }

  getToken(): string | null {
    return localStorage.getItem("token");
  }

  logout() {
    localStorage.removeItem("token");
    this.isLoginSubject.next(false);
    this.router.navigate(["login"]);
  }

  
}
//header
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenticationService } from 'src/app/services/authentication.service';
import { Observable } from "rxjs";

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
   isLoggedIn : Observable<boolean>;

  constructor(
    private authenthication: AuthenticationService,
    private router: Router
  ) { this.isLoggedIn = authService.isLoggedIn();}

  ngOnInit(): void {}

  verifyLooged() {
this.isLoggedInO.subscribe(bole=>{if(bole ==true) this.router.navigateByUrl('home'); })
// services
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, map, Observable } from 'rxjs';
import { ConfigurationService } from './configuration.service';
import { Router } from '@angular/router';
import { HeaderComponent } from '../shared/components/header/header.component';

import { BehaviorSubject, Observable } from "rxjs";

isLoginSubject = new BehaviorSubject<boolean>(this.hasToken());

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest',
    Accept: '*/*',
  }),
};

@Injectable({
  providedIn: 'root',
})
export class AuthenticationService {
  private URL_BASE: string;

  constructor(
    private configuration: ConfigurationService,
    private http: HttpClient,
    private router: Router,
  ) {
    this.URL_BASE = this.configuration.getUrlBase();
  }

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
    }),
  };
  
  
  private hasToken() : boolean {
    return !!localStorage.getItem('token');
  }

  singup(data: any) {
    return this.http.post(this.URL_BASE + 'signup', data);
  }

  login(email: string, password: string): Observable<Presocloud> {
    const user: any = {
      email: email,
      password: password,
    };
    return this.http
      .post<Presocloud>(
        this.URL_BASE + 'login',
        JSON.stringify(user),
        this.httpOptions
      )
      .pipe(
        map((res: any) => {
          this.authSuccess(res.access_token);
          return res;
        })
      );
  }
  
  isLoggedIn() : Observable<boolean> {
 return this.isLoginSubject.asObservable();
}

  authSuccess(token: string) {
    localStorage.setItem('token', token);
     this.isLoginSubject.next(true);
  }

  getToken(): string | null {
    return localStorage.getItem("token");
  }

  logout() {
    localStorage.removeItem("token");
    this.isLoginSubject.next(false);
    this.router.navigate(["login"]);
  }

  
}
//header
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenticationService } from 'src/app/services/authentication.service';
import { Observable } from "rxjs";

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
   isLoggedIn : Observable<boolean>;

  constructor(
    private authenthication: AuthenticationService,
    private router: Router
  ) { this.isLoggedIn = authService.isLoggedIn();}

  ngOnInit(): void {}

  verifyLooged() {
this.isLoggedInO.subscribe(bole=>{if(bole ==true) this.router.navigateByUrl('home'); })
se añadieron 2321 caracteres en el cuerpo
Origen Enlace
nestdan
  • 1.3k
  • 1
  • 8
  • 14

Como el formulario sera de un usuario prefiero

usuario: any = {
    email: null,
    password: null,
  };

tambien en el evento submit enviar al formulario

onSubmit(form:any): void {....}

Con las modificaciones y teniendo en cuenta este tipo de errores para acceder a valores requeridos Property 'required' comes from an index signature, so it must be accessed with ['required'].

<form (ngSubmit)="f.form.valid && onSubmit(f)" #f="ngForm" novalidate>
    <div class="form-group">
        <label for="inputEmail" class="form-label">Email address</label>
        <input type="email" class="form-control" name="email" id="email" [(ngModel)]="usuario.email" #email="ngModel"
            [ngClass]="{ 'is-invalid': f.submitted && email.invalid }" email required>

        <div *ngIf="f.submitted &&  email.invalid " class="invalid-feedback">
            <div *ngIf="email.errors?.['required']">Email is required</div>
            <div *ngIf="email.errors?.['email']">Must be a valid email address</div>
        </div>
    </div>

    <div class="form-group">
        <label for="inputPassword" class="form-label">Password</label>
        <input id="password" name="password" type="password" #password="ngModel" class="form-control"
            [(ngModel)]="usuario.password" [ngClass]="{ 'is-invalid': f.submitted && password.invalid }" minlength="8"
            required>
        <div *ngIf="f.submitted && password.invalid" class="invalid-feedback">
            <div *ngIf="password.errors?.['required']">Password is required</div>
            <div *ngIf="password.errors?.['minlength']">Password should be at least 8 characters long</div>
        </div>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>
</form>


usuario: any = {
    email: null,
    password: null,
  };
  constructor() { }

  ngOnInit(): void {
  }
  onSubmit(form:any): void {
    const { email, password } = this.usuario;
    console.log(email);
    console.log(password);
    console.log('Form value',form.value);
  }

Como el formulario sera de un usuario prefiero

usuario: any = {
    email: null,
    password: null,
  };

tambien en el evento submit enviar al formulario

onSubmit(form:any): void {....}

Con las modificaciones y teniendo en cuenta este tipo de errores para acceder a valores requeridos Property 'required' comes from an index signature, so it must be accessed with ['required'].

<form (ngSubmit)="f.form.valid && onSubmit(f)" #f="ngForm" novalidate>
    <div class="form-group">
        <label for="inputEmail" class="form-label">Email address</label>
        <input type="email" class="form-control" name="email" id="email" [(ngModel)]="usuario.email" #email="ngModel"
            [ngClass]="{ 'is-invalid': f.submitted && email.invalid }" email required>

        <div *ngIf="f.submitted &&  email.invalid " class="invalid-feedback">
            <div *ngIf="email.errors?.['required']">Email is required</div>
            <div *ngIf="email.errors?.['email']">Must be a valid email address</div>
        </div>
    </div>

    <div class="form-group">
        <label for="inputPassword" class="form-label">Password</label>
        <input id="password" name="password" type="password" #password="ngModel" class="form-control"
            [(ngModel)]="usuario.password" [ngClass]="{ 'is-invalid': f.submitted && password.invalid }" minlength="8"
            required>
        <div *ngIf="f.submitted && password.invalid" class="invalid-feedback">
            <div *ngIf="password.errors?.['required']">Password is required</div>
            <div *ngIf="password.errors?.['minlength']">Password should be at least 8 characters long</div>
        </div>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>
</form>


usuario: any = {
    email: null,
    password: null,
  };
  constructor() { }

  ngOnInit(): void {
  }
  onSubmit(form:any): void {
    const { email, password } = this.usuario;
    console.log(email);
    console.log(password);
    console.log('Form value',form.value);
  }
se eliminaron 3 caracteres en el cuerpo
Origen Enlace
nestdan
  • 1.3k
  • 1
  • 8
  • 14
Loading
se eliminaron 202 caracteres en el cuerpo
Origen Enlace
nestdan
  • 1.3k
  • 1
  • 8
  • 14
Loading
se añadieron 60 caracteres en el cuerpo
Origen Enlace
nestdan
  • 1.3k
  • 1
  • 8
  • 14
Loading
Origen Enlace
nestdan
  • 1.3k
  • 1
  • 8
  • 14
Loading