【问题标题】:Best way to pass object between siblings Angular 6在兄弟姐妹Angular 6之间传递对象的最佳方式
【发布时间】:2019-04-03 20:50:31
【问题描述】:

我希望了解将登录后产生的用户对象传递给其他组件的最佳方式。

 login() {
this.http.post<Usuario>(this.baseUrl, {
  username: this.usuario.username,
  clave: this.usuario.clave
}).subscribe(data => {
  if (data != null) {
    localStorage.setItem('isLoggedIn', 'true');
    localStorage.setItem('token', btoa(this.usuario.username + ':' + this.usuario.clave));
    this.router.navigate(['/buscador']);
    this.usuario2 = data;
    console.log(this.usuario2);

  } else {
    alert('Authentication failed.');
  }
});}

这是我登录组件中的登录方法,如果验证正确,因为我正在使用的服务返回一个用户对象,我将用户对象存储到“usuario2”中,我想知道的是最好的方法让其他组件可以访问此变量。

【问题讨论】:

标签: angular


【解决方案1】:

某处

# Simple passing of data between components using a dedicated data service

export class LoginService {

  username: string;

  getUsername(): string {
    return this.username;
  }

  setUserName(username: string) {
    this.username = username
  }

}

# Using a behavior subject so other active components are updated with the new value whenever it changes.

export class LoginService {

  username: BehaviorSubject<string> = new BehaviorSubject<string>("");;

  watchUsername(): BehaviorSubject<string> {
    return this.username;
  }

  setUserName(username: string) {
    this.username.next(username);
  }

}

# You can then consume the Behavior subject like this

this.loginService.watchUserName.subscribe(val => console.log(val));

【讨论】:

    【解决方案2】:

    我认为这里最好的开发模式是创建LoginService,这是一个包含所有身份验证/本地存储逻辑的服务(https://angular.io/guide/architecture-services)。服务模式之所以有益的原因有很多;

    1. 它为您正在扩展的所有功能提供了一个干净的界面;因此,如果您决定稍后更改实现,则无需查找所有调用站点即可执行此操作。

    2. 同样,您可以在运行时轻松交换实现,以便模拟服务。例如,您可以创建在非生产模式下使用的MockLoginService,它会打印调试数据并访问本地服务器而不是生产服务器。

    3. 您可以使用依赖注入,因此在任何给定模块中都可以轻松访问它。

    【讨论】:

    • 在这种情况下,使用 BehaviorSubject 将数据存储在服务中并将其公开公开为 Observable 以便订阅更改也很有用。
    • @Mike 绝对 - 这样你就可以将它直接传递到 async 管道!
    • 所以如果我理解正确的话,你的意思是我应该在服务中做逻辑,然后使用依赖注入来访问用户的值?
    • 我按照您的建议使用共享服务使其工作,谢谢!但是您知道我怎样才能让父母知道“usuario2”对象的变化吗?我期待找到用户登录后导航栏消失的方法。
    • @FlavioAlarcon 正如 Mike 所说 - 创建一个返回布尔可观察对象的 isLoggedIn() 方法。然后只需将*ngIf="userService.isLoggedIn() | async 添加到您的导航栏。
    猜你喜欢
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 2023-02-10
    • 2020-01-31
    相关资源
    最近更新 更多