javascript - 如何在 Angular 的服务和组件之间共享数据?
问题描述
如何实时绑定服务和组件之间的数据。
让我们假设isAuthenticated
身份验证服务的公共变量正在影响组件中的某些视图。我的问题是如何订阅isAuthenticated
变量?
服务:
import { Injectable } from '@angular/core';
@Injectable()
export class Authentication {
isAuthenticated:boolean = false;
login() {
localStorage.setItem('access_token', 'true');
this.isAuthenticated = true;
}
}
零件:
...
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
private isAuthenticated:boolean = false;
constructor(public authService: Authentication) {
this.isAuthenticated = this.authService.isAuthenticated'
}
}
主页.html
...
<div *ngIf="isAuthenticated">Authentication view</div>
<div *ngIf="!isAuthenticated">Unauthentication view</div>
...
通过上面的当前流程,绑定运行良好,但不是实时的。
那么最好的方法是什么:
1- 在 Authentication 服务中创建一个 observable,以便在组件中订阅它。
2-使用以下方式绑定:
...
<div *ngIf="authService.isAuthenticated">Authentication view</div>
<div *ngIf="!authService.isAuthenticated">Unauthentication view</div>
...
第二种方法效果很好,但我不知道这是否是最佳做法。
谢谢。
解决方案
我建议使用BehaviorSubject
. 它是一个Observable
,所以你可以订阅它,但你也可以通过调用来控制它何时发出新值behaviorSubject.next(newValue)
。创建 BehaviorSubject 时,您必须将初始值传递给它。在你的情况下,它是false
.
@Injectable()
export class Authentication {
isAuthenticated = new BehaviorSubject<boolean>(false);
login() {
localStorage.setItem('access_token', 'true');
this.isAuthenticated.next(true);
}
}
-
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
private isAuthenticated:boolean;
constructor(public authService: Authentication) {
this.authService.isAuthenticated
.subscribe(isAuthenticated => this.isAuthenticated = isAuthenticated)
}
}
或者您可以使用 Async Pipe 订阅 html
export class HomePage {
private isAuthenticated: BehaviorSubject<boolean>;
constructor(public authService: Authentication) {
this.isAuthenticated = this.authService.isAuthenticated;
}
}
-
<div *ngIf="isAuthenticated | async">Authentication view</div>
<div *ngIf="!(isAuthenticated | async)">Unauthentication view</div>
与常规的 Observable 不同,当您在 BehaviorSubject 上调用 subscribe 时,您作为参数传递给 subscribe 的函数将立即执行。这是因为 BehaviorSubject 总是有一个值。您可以使用它来访问它,this.authService.isAuthenticated.value
但它在这里不是很有用。
推荐阅读
- angular - NGRX 效果 - 分派的动作不按顺序执行
- java - Spring Boot 应用程序之间的 REST 通信
- assembly - 在引导加载程序中 JMPing 到 0x7C00 不会导致无限循环
- python-3.x - 按日期和名称对列进行分组,并使用 python pandas 获取最小值及其开始和结束
- c# - 无法为不写入数据的操作设置 Content-Length 或 Chunked Encoding 我该怎么办?
- javascript - 部署函数时,哪些文件会发送到 Firebase 云函数环境?
- flutter - 集团和水合集团冲突
- javascript - 如何从对象数组中检索选择性属性并使用javascript存储为对象?
- yaml - 使用snakemake映射读取
- c# - 从程序集中获取隐式实例化的泛型类型?