angular - passing variable values from one page.ts to another

Asked

Viewed 31 times

-2

I’m starting now with the angular and I’m having a doubt, I made a canvas of login.page.html, after the back-end confirms the login and password the user goes to the screen home.page.html on this screen the user will have access to a query menu, each user will make his query with his login/password, but the angle by which I saw works with classes and if I set the login and password in loginpage class and instantiate that class in the class Homepage the value of var login and var password if you lose, I read that there are several ways to do injection, service but I could not apply or understand any of these concepts, someone to explain me?

import { Component, Inject, OnInit } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router';
import { AlertController, MenuController } from '@ionic/angular';



@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {

public folder: string;
public login: string;
public senha: string;

constructor(
    //private activatedRoute: ActivatedRoute,
    private http: HttpClient,
    private alertController: AlertController,
    private menu: MenuController,
    private router: Router

){

}

async ngOnInit() {

}

async alert(mensagem: string){
    const alert = this.alertController.create({
        header: 'Aviso', message: mensagem,buttons: ['Ok']
      });
    (await alert).present();
}

public conectar() {
    let postData = { "log_login": this.login, "log_senha": this.senha };

    this.http.post<any>(                                                        // Requisição Ajax
        "http://localhost/appBTR/conectar.php",                                 // URL
        JSON.stringify(postData))                                               // Parametros
        .subscribe(                                                             // Retorno
            async data => {                                                     // Caso success
                if( data == 0){                                                 // Login e/ou Senha inválidos!
                    this.alert("Login e/ou Senha inválidos!");                  // Aviso na tela
                }
                else{ this.telaInicio(postData); }                                      // Caso login ok
            },
            async (error: HttpErrorResponse) => {                               // Caso error
                this.alert(error.error.text);
            }
        );
}

telaInicio(postData: object){
    
    // AQUI EU PRECISO DAR UM JEITO DE OU ENVIAR O posData para a home.page.ts
    // OU TRANSFORMA-LO EM GLOBAL
    this.menu.enable(true,'main-menu');
    this.router.navigate(['home']);
}

}
  • I don’t know if you are taking a course (I recommend), or learning on your own, but this part of login goes much deeper in a real application. Generally (if not totally) the user data (login, password, etc...) is stored in the user session generating an authentication token, jwt and all that stuff, then when you need this data you get it at the front by the API, security issue.

  • Who negative could say in words what is wrong in the question?

1 answer

0

An answer to that question is here https://www.youtube.com/watch?v=Mz8lb81AAe4

But this in English, only copying the code I could understand that it is possible to make a class with @Injectable set in the providers of app.modulets. and do the import where you need to use.

I also saw that it is possible using token I managed to copy and paste and rotated, but it was not intelligible for me, if someone can contribute I will leave open the question because I do not know what are the differences, advantages etc...

connexion.service.ts

import { Injectable } from '@angular/core';
import { Conexao } from './conexao.modal';

@Injectable({
    providedIn: 'root'
})

export class ConexaoService {

    private conexao: Conexao;

    constructor() { }

    setConexao(conexao: Conexao){
        this.conexao = conexao;
    }

    getConexao(){
        return this.conexao;
    }
}

In the app.modulets.

...
@NgModule({
...
   providers: [ConexaoService]
...
({

login.pagets.

import { ConexaoService } from './../share/conexao.service';
import { Conexao } from '../share/conexao.modal';

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})

export class LoginPage implements OnInit {
   constructor(private conexaoService: ConexaoService){

   }
   ...
   telaInicio(postData: Conexao){
      // AQUI PASSO O VALOR QUE IRÁ FICAR COMO GLOBAL E ACESSIVEL NA PAGINA INICIO (HOME) APÓS O LOGIN
      this.conexaoService.setConexao(postData); 
      this.router.navigate(['inicio']);
   }
}

homePge (home)

import { ConexaoService } from './../share/conexao.service';

@Component({
    selector: 'app-inicio',
    templateUrl: './inicio.page.html',
    styleUrls: ['./inicio.page.scss']

})
export class InicioPage implements OnInit {

    constructor(
        private menu: MenuController,
        private ConexaoService: ConexaoService
    ){

    }

    ngOnInit() {
        this.menu.enable(true, 'main-menu');

        // AQUI É COMO USARIA O VALOR PASSADO DA TELA 'login' para a tela 'inicio'
        console.log("conexao " + this.ConexaoService.getConexao().log_login); 
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.