Visibility of components based on the value of a variable in Angular 4

0

Good morning. I am making an application in Angular 4, which makes an http request to an API to perform the initial login, so that, if the request gives a result, the private part of the application becomes visible.

Next I show the code of the service that makes the request:

import { Injectable } from '@angular/core';
import { Http, Response, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable} from 'rxjs/Observable';

@Injectable()
export class loginService{

    public url:string;
    public autenticado:boolean;

    constructor(private _http:Http){
       this.url = "url de la API";
    }

    getValAuth(){
        console.log("Get Val:"+this.autenticado);
    }

    getLogin(data:any){

        this.url = this.url+"?param + datos procedentes del formulario de login;
        return this._http.get(this.url, {params: data})
            .map(res => res.json());


    }
}

And then I show the component where the service is injected:

import { Component } from '@angular/core';
import {LoginModel} from './login.model';
import { loginService } from '../services/login.service';

@Component({
  selector: 'form-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [loginService]
})
export class loginComponent {

  public inicio_Sesion:LoginModel;

  constructor(private _resultado:loginService){
    this.inicio_Sesion = new LoginModel("","");
  }

  ngOnInit(){

  }

  onSubmit(isValid:boolean){  
   this._resultado.getLogin(this.inicio_Sesion).subscribe(
     result=>{
        if(result.count == 1){
          this._resultado.autenticado = true;
        }else{
          this._resultado.autenticado = false;
        }
     },
     error=>{
       var errorMessage = <any>error;
       console.log(errorMessage);
     }
   );

  }


}

And in the app.component I have the complete structure, which has to show one part or another depending on the result of the HTTP call.

                                                                 

Any suggestions that can guide me on how to do this? Thank you very much in advance.

    
asked by AntonioMP87 28.11.2017 в 21:22
source

1 answer

0

I advise you to use Angular's routing features. You can activate them using:

ng new mi-aplicacion --routing true

You will have to define a routing file for the root component (app-module) and for the rest of the components you want to route ( redirect ). p>

This way you can check your Boolean variable of successful login redirecting to a new component that contains the private part.

Even so, I advise you to control the routes with a session token to improve the security of your application.

Here is a link where it explains in a simple way how to route with Angular. link

    
answered by 01.12.2017 / 00:34
source