【问题标题】:Angular await service between components, Behavior Subject组件之间的角度等待服务,行为主题
【发布时间】:2025-12-02 19:20:05
【问题描述】:

当我刷新窗口时,我的 Angular 网上商店出现问题,我创建了一个从服务器获取用户数据的服务,然后使用 BehaviorSubject 注入到“产品”部分,我的目标是只发出一个请求到服务器:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private userId = new BehaviorSubject<any>('');
  currentUserId = this.userId.asObservable();

  constructor() { }
  
  sendUserId(message: string){
    this.userId.next(message)
  }
}

这工作正常,但问题是当我刷新产品部分的窗口时,在控制台中我可以看到服务获取用户数据,但是当我 getProducts() 它抛出一个错误时,似乎 getProducts() 使在服务得到响应之前请求,我需要用户 ID 来提出产品请求。我的问题:有没有办法等待 BehaviorSubject 的响应,然后发出 getProducts() 请求?这是产品部分的代码:

ngOnInit(): void {
    this._dataService.currentUserId.subscribe(userId => this.userId = userId);

    if(this.userId.length === 0){
      this.userService.getUserProfile().subscribe(
        res => {
          this.userDetails = res['user'];
          this.userId = this.userDetails._id;
          this.getProducts();          
        },
        err => { 
          console.log(err);           
        }
      );
    } else {
      this.getProducts();
    } 
  }

如您所见,我做了一个条件来检查 userId 是否存在,如果不存在,我必须提出新的用户请求,这修复了错误,但我认为有更好的方法来解决这个问题。提前致谢。

【问题讨论】:

标签: javascript angular


【解决方案1】:

如何将所有逻辑放在observernext 函数中,如下所示:

this._dataService.currentUserId.subscribe(userId => {
  if (userId.length === 0)
  {
    this.userService.getUserProfile().subscribe(
      res => {
        this.userDetails = res['user'];
        this.userId = this.userDetails._id;
        this.getProducts();
      },
      err => {
        console.log(err);
      }
    );
  } else
  {
    this.getProducts();
  }
});

【讨论】: