【问题标题】:Getting an empty array on subscribing an observable在订阅 observable 时获取一个空数组
【发布时间】:2021-07-22 16:35:59
【问题描述】:

从服务订阅对象时,我在组件中得到一个空数组。 我使用了主题行为并尝试将数据从主题传递到组件,但在组件上返回一个空数组。

服务:-

allPassedData: BehaviorSubject<any> = new BehaviorSubject<any>([]);
  
searchDepartments() {
    const fetchData3 = this.db.todos.orderBy('department').keys((departments) => {
      alert("Departments are: " + departments.join(','));
      console.log(departments);   //<============== ["data","accounts"]
      console.log(typeof departments);      //<========== object
      this.allPassedData.next(departments);
    });
  }

  getDep(): Observable<any[]> {
    return this.allPassedData.asObservable();
  }

组件

  showTable() {
    this.todoService.getDep().subscribe((departments)=>{
      this.showDepartments = departments;
      console.log(this.showDepartments);   <=============== [] empty
    })

【问题讨论】:

  • 你也应该订阅searchDepartments,否则它不会做任何事情。此外,您正在使用带有空数组初始值的 BehaviorSubject,这就是您在日志中看到的内容
  • @PoulKruijt 我应该在初始时传递什么而不是空数组?据我所知BehaviorSubject 首先取初始值,但在这里我该怎么办?
  • A ReplaySubject(1) 最适合这个。然而,为什么会有searchDepartmentsgetDepallPassedData 有点令人困惑。感觉这样的都可以合二为一
  • @PoulKruijt 好的,我将与ReplaySubject(1) 联系,尽管目前我已经通过 Promise 解决了这个问题。我在下面添加了我的答案
  • 混合promise 和observables 有点反模式,而且如果你使用其中一个也没关系。这同样适用于subscribe

标签: angular rxjs behaviorsubject


【解决方案1】:

试试这样的方法:

服务

departments$ = this.db.todos.orderBy('department').keys((departments) => {
      alert("Departments are: " + departments.join(','));
      console.log(departments);   
      console.log(typeof departments);      
    });
  }

组件

  showTable() {
    this.todoService.departments$.subscribe((departments)=>{
      this.showDepartments = departments;
      console.log(this.showDepartments);   
    })

不需要第二个 Observable (BehaviorSubject),因为 API 调用已经返回了一个您可以使用的 Observable。

更好的是,像这样改变它:

组件

departments$ = this.todoService.departments$;

模板

*ngFor = "let dept of departments$ | async"

使用声明性方法可确保 UI 与发送到流中的任何内容自动同步。

有关声明式/反应式方法的更多信息,请参阅此处的第一次演讲:https://www.youtube.com/watch?v=iSsch65n8Yw

【讨论】:

  • 如果我想将departments$ 保留在一个函数中,因为我得到Property 'db' is used before its initialization.
【解决方案2】:

我使用 Promise 解决了这个问题

searchDepartments(){
    return this.db.todos.orderBy('department').keys((departments) => {
      alert("Departments are: " + departments.join(','));
      console.log(departments);   
      console.log(typeof departments);    
      if (departments && departments.length != 0) {
        return departments;
      } else {
        return undefined;
      }
    }); 
  }

并且在DeborahK 建议的组件中。

async showTable() {
    this.connection = await this.todoService.searchDepartments();
    console.log(this.connection);
 }

【讨论】:

    猜你喜欢
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    相关资源
    最近更新 更多