【发布时间】:2020-06-19 03:44:59
【问题描述】:
我在 Angular 中遇到了 observables 的问题。我想我要么遗漏了一些东西,要么我没有正确理解它。我正在尝试跟踪用户是否登录。为此,我有一个 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>
【问题讨论】:
-
of(this.authenticated)不会以某种方式跟踪this.authenticated的变化值,它会在调用getAuthenticated的那一刻发出值,然后完成。如果您想随着时间的推移公开对该值的更改流,请查看主题。 Here's 我写的一篇博客文章,介绍了一种从主题中公开可观察对象的方法。 -
不知道为什么这个问题被否决,这是一个合法的问题(所以我投了赞成票)。你接近“想法”,但正如乔恩所说。一个主题,或者在这种情况下甚至可能是一个 BehaviourSubject 将解决这个问题。
-
啊,谢谢各位。我花了一些时间阅读 observables,我想我现在更好地理解了它们(并且因为以前没有这样做而感到愚蠢)。我看到我完全错误地使用它们。目前,我在服务中将
authenticated设为私有并提供了一个getter,它现在满足了我根据用户是否登录来更改视图的要求。我会用我的解决方案更新这篇文章。
标签: angular typescript