【问题标题】:Calling services in the correct order in Angular 4?在 Angular 4 中以正确的顺序调用服务?
【发布时间】:2017-10-17 15:47:04
【问题描述】:

这是我的项目布局:

这里是返回用户ID的用户数据服务函数:

get uid(): BehaviorSubject<string> {
    const uidSubject: Subject<string> = new Subject<string>();
    this.afAuth.authState.subscribe((data) => {
      uidSubject.next(data.uid);
    });
    return uidSubject;
  }

然后这里是用户任务服务,它使用之前服务的 ID 获取任务:

  get tasks(): BehaviorSubject<string> {
    const tasksSubject: BehaviorSubject<string> = new BehaviorSubject<string>('no tasks available');
    this.afs.collection(`users/${this.uid}/tasks`).valueChanges().subscribe(tasks=> {
      if (tasks.length !== 0) {
        tasksSubject.next(tasks);
      }
    });
    return tasksSubject;
  }

然后我在 App 组件中订阅以从任务服务获取数据,但用户 ID 显然是 undefined,因为任务函数在 uid 函数之前被调用。

那么如何确保用户数据服务在调用任务服务之前获得uid

【问题讨论】:

    标签: angular firebase angularfire angular2-services angular-services


    【解决方案1】:

    我想一个解决方案是使用 Observable 的flatMap。 像这样的东西(我重写了你的代码,但我无法测试它)

    get uid(): BehaviorSubject<string> {
      const uidSubject: Subject<string> = new Subject<string>();
      return this.afAuth.authState
    }
    
    get tasks(uid): BehaviorSubject<string> {
      const tasksSubject: BehaviorSubject<string> = new BehaviorSubject<string>('no tasks available');
      return this.afs.collection(`users/${uid}/tasks`).valueChanges()
    }
    
    caller() {
      this.uid().flatMap( data => {
        //pass data as parameter, will be the id
        return this.tasks(data)
      })
      .subscribe( tasks => {
         //do what you need
      })
    }
    

    关于这个有这个good thread

    【讨论】:

    • 谢谢,但是,我真的很想避免同时导入这两个服务,并避免使用大量逻辑使应用程序组件混乱,这样我就可以构建我的项目组件以仅显示数据(用于测试目的)。那么您是否认为将我的逻辑拆分为多个服务是一个坏主意,而我只需要将它们组合成一个即可避免问题吗?
    • 我看不出避免导入/注入多个服务的意义。服务应该具有“专门”的方法,以便更容易解耦和重用它们。当然,您可以只编写一项具有大量逻辑的服务,但您将错过这些好处的重点。无论如何,这对于您提到的这种情况并不重要,您需要按顺序调用方法(返回 Observables)。 flatMap 将为您提供帮助。
    猜你喜欢
    • 2018-01-30
    • 1970-01-01
    • 2016-04-02
    • 2017-06-21
    • 2020-01-07
    • 2013-07-05
    • 2017-01-19
    • 1970-01-01
    • 2016-03-21
    相关资源
    最近更新 更多