Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果用户登录,则隐藏元素_Javascript_Angular_Typescript_Firebase_Firebase Authentication - Fatal编程技术网

Javascript 如果用户登录,则隐藏元素

Javascript 如果用户登录,则隐藏元素,javascript,angular,typescript,firebase,firebase-authentication,Javascript,Angular,Typescript,Firebase,Firebase Authentication,我有一个app.component.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class='container'> <ul class="nav navbar-nav"> <li class='nav-item'> <a class='nav-link' routerLink="/">Strona

我有一个
app.component.html

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class='container'>
    <ul class="nav navbar-nav">
      <li class='nav-item'>
        <a class='nav-link' routerLink="/">Strona główna</a>
      </li>
      <li class='nav-item'>
        <a class='nav-link' routerLink="/about">O nas</a>
      </li>
      <li class='nav-item' *ngIf='!user'>
        <a class='nav-link' routerLink="/login">Zaloguj</a>
      </li>
      <li class='nav-item' *ngIf='!user'>
        <a class='nav-link' routerLink="/register">Zarejestruj</a>
      </li>
      <li class='nav-item' *ngIf='user'>
        <a class='nav-link' routerLink="/logout">Wyloguj</a>
      </li>
    </ul>
  </div>
</nav>
<main>
  <router-outlet></router-outlet>
</main>
doLogin
功能示例:

doLogin(value){
  return new Promise<any>((resolve, reject) => {
    firebase.auth().signInWithEmailAndPassword(value.email, value.password)
    .then(res => {
      resolve(res);
    }, err => reject(err))
  })
}
doLogin(值){
返回新承诺((解决、拒绝)=>{
firebase.auth().signiWithEmailandPassword(value.email,value.password)
。然后(res=>{
决议(res);
},err=>拒绝(err))
})
}

我是个新手。到目前为止,我主要是在Express工作。我在考虑设置一个会话变量之类的东西,以便在用户是否登录时保留它。如何在Angular中执行此操作?

只需在组件级别设置一个变量isLoggedIn(或在整个应用程序中访问它的LocalStorage)。用户成功通过身份验证后,可以将其设置为true/false


在组件级别上使用
*ngIf
可以显示基于登录名的任何信息只需在组件级别设置一个变量isLoggedIn(或在整个应用程序中访问它的本地存储)。用户成功通过身份验证后,可以将其设置为true/false


在组件级别上使用
*ngIf
来显示基于登录的任何信息,在组件中,您可以有一个保存用户登录状态的变量。因此,在导航到
/user
路线的同时,您还需要执行
此操作。isAuthenticated=true
,如下所示

当您退出时,请确保将此设置为false

this.isAuthenticated = false;
这可能是示例组件代码:

import {Component} from '@angular/core';
import {AuthService} from '../core/auth.service';
import {Router, Params} from '@angular/router';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

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

export class LoginComponent {
  isAuthenticated:boolean = false;
  loginForm: FormGroup;
  errorMessage: string = '';

  constructor(
    public authService: AuthService,
    private router: Router,
    private fb: FormBuilder
  ) {
    this.createForm();
  }

  createForm() {
    this.loginForm = this.fb.group({
      email: ['', Validators.required],
      password: ['', Validators.required]
    });
  }

  tryFacebookLogin() {
    this.authService.doFacebookLogin()
      .then(res => {
        this.isAuthenticated = true;
        this.router.navigate(['/user']);
      });
  }

  tryTwitterLogin() {
    this.authService.doTwitterLogin()
      .then(res => {
      this.isAuthenticated = true;
        this.router.navigate(['/user']);
      });
  }

  tryGoogleLogin() {
    this.authService.doGoogleLogin()
      .then(res => {
      this.isAuthenticated = true;
        this.router.navigate(['/user']);
      });
  }

  tryLogin(value) {
    this.authService.doLogin(value)
      .then(res => {
        this.isAuthenticated = true;
        this.router.navigate(['/user']);
      }, err => {
        this.isAuthenticated = false;
        console.log(err);
        this.errorMessage = err.message;
      });
  }

  logOut(){
    //write logout from server here
    this.isAuthenticated = false;
  }
}
然后在模板上执行以下操作

<div *ngIf="isAuthenticated>Show Logout button</div>
<div *ngIf="!isAuthenticated">Show Login button</div>

在组件中,您可以有一个保存用户登录状态的变量。因此,在导航到
/user
路线的同时,您还需要执行
此操作。isAuthenticated=true
,如下所示

当您退出时,请确保将此设置为false

this.isAuthenticated = false;
这可能是示例组件代码:

import {Component} from '@angular/core';
import {AuthService} from '../core/auth.service';
import {Router, Params} from '@angular/router';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

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

export class LoginComponent {
  isAuthenticated:boolean = false;
  loginForm: FormGroup;
  errorMessage: string = '';

  constructor(
    public authService: AuthService,
    private router: Router,
    private fb: FormBuilder
  ) {
    this.createForm();
  }

  createForm() {
    this.loginForm = this.fb.group({
      email: ['', Validators.required],
      password: ['', Validators.required]
    });
  }

  tryFacebookLogin() {
    this.authService.doFacebookLogin()
      .then(res => {
        this.isAuthenticated = true;
        this.router.navigate(['/user']);
      });
  }

  tryTwitterLogin() {
    this.authService.doTwitterLogin()
      .then(res => {
      this.isAuthenticated = true;
        this.router.navigate(['/user']);
      });
  }

  tryGoogleLogin() {
    this.authService.doGoogleLogin()
      .then(res => {
      this.isAuthenticated = true;
        this.router.navigate(['/user']);
      });
  }

  tryLogin(value) {
    this.authService.doLogin(value)
      .then(res => {
        this.isAuthenticated = true;
        this.router.navigate(['/user']);
      }, err => {
        this.isAuthenticated = false;
        console.log(err);
        this.errorMessage = err.message;
      });
  }

  logOut(){
    //write logout from server here
    this.isAuthenticated = false;
  }
}
然后在模板上执行以下操作

<div *ngIf="isAuthenticated>Show Logout button</div>
<div *ngIf="!isAuthenticated">Show Login button</div>
Firebase提供了一个贯穿整个库的。将连接结果存储到可以显示的变量中

import * as firebase from 'firebase/app';

randomFunction() {
  firebase.auth().onAuthStateChanged(user => {
    if(user) {
      this.logged = true;
    } else {
      this.logged = false;
    }
  });
}
在HTML中

<div *ngIf="logged; else #isAnonymous">
  <button>Log out</button>
</div>
<ng-template #isAnonymous>
  <button>Log in</button>
</ng-template>

注销
登录
Firebase提供了一个贯穿整个库的。将连接结果存储到可以显示的变量中

import * as firebase from 'firebase/app';

randomFunction() {
  firebase.auth().onAuthStateChanged(user => {
    if(user) {
      this.logged = true;
    } else {
      this.logged = false;
    }
  });
}
在HTML中

<div *ngIf="logged; else #isAnonymous">
  <button>Log out</button>
</div>
<ng-template #isAnonymous>
  <button>Log in</button>
</ng-template>

注销
登录

正如您在接受答案的评论中所问,您决定使用LocalStorage策略验证用户是否登录

我建议您创建一个服务来管理所有身份验证内容:

auth.service.ts

import { LocalStorageService } from 'angular-2-local-storage';

@Injectable()
export class AuthService {

  constructor(private http: Http, private localStorage: LocalStorageService) { }

 login(email: string, password: string): Observable<any>{
   //  Do Stuff  .....;
   //  if successfull set to LocalStorage
}

  isAuthenticated(): boolean{
    if (this.localStorage.get('isLoggedIn')){
      return true;
    }
    else{
      return false;
    }
  }

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

  constructor(private authService: AuthService) { }
  let isLoggedIn = false;    


  ngOnInit() {

    isLoggedIn  = this.authService.isAuthenticated();

    if (isLoggedIn){
      alert('hello');
    }
  }

现在,您可以将模板中的变量
isLoggedIn
*ngIf
一起使用,正如您在接受答案的评论中所问的那样,您决定使用LocalStorage策略来验证用户是否登录

我建议您创建一个服务来管理所有身份验证内容:

auth.service.ts

import { LocalStorageService } from 'angular-2-local-storage';

@Injectable()
export class AuthService {

  constructor(private http: Http, private localStorage: LocalStorageService) { }

 login(email: string, password: string): Observable<any>{
   //  Do Stuff  .....;
   //  if successfull set to LocalStorage
}

  isAuthenticated(): boolean{
    if (this.localStorage.get('isLoggedIn')){
      return true;
    }
    else{
      return false;
    }
  }

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

  constructor(private authService: AuthService) { }
  let isLoggedIn = false;    


  ngOnInit() {

    isLoggedIn  = this.authService.isAuthenticated();

    if (isLoggedIn){
      alert('hello');
    }
  }


现在,您可以将模板中的变量
isLoggedIn
*ngIf

一起使用,您可以在登录成功时将变量设置为localstorage,并在应用程序的任何位置在登录和注销时将其检索。登录成功后,您可以将变量设置为localstorage并检索它在应用程序中的任何位置,登录和注销时的Angular blog都很好地解释了这一点,因此,如果我在
app.component.ts
中创建变量,我可以在
auth.service.ts
中更改它吗?一个完全不同的地方。或者我必须使用localStorage?localStorage是一种选择,因为变量不能在服务中使用,因为它们位于不同的上下文中。如果您试图访问不同组件中的变量,则需要创建一个
服务
,允许每个组件之间传输数据。或者您可以使用本地存储。签出@JuanDM好的,我让localstorage工作了,但是如何比较
*ngIf
中的localstorage变量呢?我是作为答案发布的。因此,如果我在
app.component.ts
中创建变量,我可以在
auth.service.ts
中更改它吗?一个完全不同的地方。或者我必须使用localStorage?localStorage是一种选择,因为变量不能在服务中使用,因为它们位于不同的上下文中。如果您试图访问不同组件中的变量,则需要创建一个
服务
,允许每个组件之间传输数据。或者您可以使用本地存储。签出@JuanDM好的,我让localstorage工作了,但是如何比较
*ngIf
中的localstorage变量呢?我作为应答者发布了,我应该把这段代码放在
app.component.ts
文件中,对吗?你可以把它放在你想显示/隐藏的地方,具体取决于用户状态。在您的情况下,是的,我想它就在那里,因为它是您提供的唯一HTML代码!是的,我忘了在问题中加上它。我有一个简单的路由系统,我需要这个变量,它在每个页面上都可用。然后创建一个共享服务。您可以了解它是什么,我应该将此代码放在
app.component.ts
文件中,对吗?您可以根据用户状态将其放在要显示/隐藏内容的位置。在您的情况下,是的,我想它就在那里,因为它是您提供的唯一HTML代码!是的,我忘了在问题中加上它。我有一个简单的路由系统,我需要这个变量,它在每个页面上都可用。然后创建一个共享服务。你可以知道那是什么,那正是我要找的!谢谢,如果要隐藏的元素位于主组件上,而sigIn位于另一个组件中,该怎么办?这个解决方案行不通!我无法理解您的评论,请参见
authService
作为验证用户是否经过身份验证的帮助,您可以在任何需要的地方插入此服务,并调用
isAuthenticated
方法,您能更好地解释您的观点吗?这正是我想要的!谢谢,如果要隐藏的元素位于主组件上,而sigIn位于另一个组件中,该怎么办