首页 > 解决方案 > 如何在 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>
...

第二种方法效果很好,但我不知道这是否是最佳做法。

谢谢。

标签: javascriptangulartypescriptionic-frameworkdata-binding

解决方案


我建议使用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但它在这里不是很有用。


推荐阅读