Angular订阅不返回布尔值?

时间:2020-06-18 17:17:52

标签: angular typescript

我在Angular中遇到可观察的问题。我认为我正在丢失某些东西,或者我不太了解它。我正在尝试跟踪用户是否登录。为此,我有一个AuthService,该服务具有布尔值以跟踪用户是否通过了身份验证。下面我有一个非常简单的AuthService版本,我想做的就是更改已验证的布尔值。但是,这种变化并未反映在任何组件中。我已验证该服务中的值正在更改,但是该更改不会传递给任何订户。

AuthService.ts

import { Injectable } from '@angular/core';
import { of, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class GoogleauthService {

  authenticated: boolean = false;
  access_token: string;

  constructor() { }

  isAuthenticated(): Observable<boolean>{
    return of(this.authenticated);
  }

  toggleAuthenticate(): void{
    this.authenticated = !this.authenticated
  } 

}

LoginComponent.ts

import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { GoogleauthService } from 'src/app/services/googleauth/googleauth.service';

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

  auth2: any;
  public authenticated: boolean;

  constructor(private googleAuthService: GoogleauthService) { }

  @ViewChild('loginRef', {static: true }) loginElement: ElementRef;

  ngOnInit(): void {
    // this.googleSDK();
    this.getAuthenticated();
  }

  getAuthenticated(): void{
    this.googleAuthService.isAuthenticated().subscribe((bool) => {this.authenticated = bool;});
  }

  Authenticate(): void{
    this.googleAuthService.authenticated = !this.googleAuthService.authenticated;
    // this.googleAuthService.toggleAuthenticate();
  }

}

LoginComponent.html

<div class="container mt-5">
    <h2>{{authenticated}}</h2>
    <div class="row mt-5">
      <div class="col-md-4 mt-2 m-auto ">
          <!-- <button class="loginBtn loginBtn--google" #loginRef>
              Login with Google
          </button> -->
          <button (click)="Authenticate()">
            Authenticate
          </button>
      </div>    
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

因为变量已通过身份验证,所以保持不变,则为false,并且订阅不返回值,使用void函数则此类型不返回值。

使用 localStorage 这种方法最好检查用户是否已登录。

login(email,password){
this.fbAuth.signInWithEmailAndPassword(email,password)
    .then(async user =>{
 await localStorage.setItem('userData', JSON.stringify(user)) 
})
//your code 
}
isAuthenticated()(){
  const luserData = localStorage.getItem('userData');
   return suserData !==null  ? true : false 
}
logout() {
    localStorage.removeItem('userData');
    localStorage.clear();
    //your code  
    );   
}

希望这会有所帮助。