繁体   English   中英

Angular 等待组件间服务,行为主体

[英]Angular await service between components, Behavior Subject

当我刷新 window 时,我的 Angular web 商店中有一个问题,我创建了一个服务,该服务从服务器获取用户数据,然后注入到“产品”部分,以提出一个请求:

 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) } }

这工作正常,但问题是当我在产品部分刷新 window 时,在控制台中我可以看到该服务获取用户数据但是当我 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 是否存在,如果不存在,我必须提出新的用户请求,这修复了错误,但我认为有更好的方法来解决这个问题。 提前致谢。

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

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();
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM