订阅可观察对象时获取空数组

时间:2021-07-22 16:35:59

标签: angular rxjs behaviorsubject

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

服务:-

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我用 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);
 }