【问题标题】:Display username in the profile section in the navbar在导航栏中的配置文件部分显示用户名
【发布时间】:2022-02-03 18:54:53
【问题描述】:

我正在尝试在导航栏中显示用户名。我设法使用我的个人资料服务来做到这一点:

let user of profileService.getProfile(),它使用订阅来检索数据。

但是,我第一次登录时,该名称不会弹出。如果我刷新浏览器,将显示名称。我想这与订阅及其异步性质有关,但如果是这种情况,那么解决问题的最佳方法是什么?

【问题讨论】:

  • 配置文件信息是否存储在localStorage中?您在何时何地设置信息,即profileService.setProfile(),然后用于getProfile()
  • 不,我不将信息存储到 localStorage。我所拥有的直接是 getProfile,它是调用 api 的 http 方法。 api 返回一个包含我需要的信息的 json。但是,http get 方法返回另一种类型(我认为是 Observable),而我发现“获取”(但不将其存储到我更喜欢的变量中)的唯一方法是订阅。

标签: node.js angular asynchronous subscribe


【解决方案1】:

正如您在评论中提到的,您的 getProfile() 返回一个 observable。 你可以在你的组件中subscribe给它,然后在你的HTML组件中显示用户名:

userName: string;

constructor(private profileService: ProfileService){}

ngOnInit(): void { 
   this.profileService.getProfile().subscribe((resp)=>{
      //Assuming response only returns username
      this.userName = resp;
   });
}

然后在您的 HTML 中,您可以绑定到 userName。

 <div>
    Logged in user name is: {{userName}} 
 </div>

【讨论】:

    【解决方案2】:

    我认为你可以在服务中创建一个 BehaviorSubject,它有一个方法 getValue() 可以提供当前值:

    user$ : BehaviorSubject<String> = new BehaviorSubject("");
    
    setProfile() {
        this.user$.next("newName");
    }
    
    getProfile(): string {
        return this.user$.getValue();
    }
    

    在 View 中,您可以使用管道 (AsyncPipe) 来订阅 observable,例如:

    {{ userOfProfileService$ | async }}
    

    但是,您也可以在没有 getProfile() 的情况下使用 Subject observable,而只在视图中使用 AsyncPipe。

        user$ : Subject<String> = new Subject();
    

    【讨论】:

    • 我正在使用我的api,所以profileService使用http来获取信息,所以我不确定我是否可以使用这个(?)
    • 在 setProfile() 中您可以请求 api 并在 subscribe 中写入 this.user.next("newName");
    • 您能详细说明一下吗?我对 Angular/js/async 有点陌生...
    • setprofile() { this.http.get(urlGetProfile).subscribe(result => this.user.next("newName")) } 欢迎来到新世界?跨度>
    猜你喜欢
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多