Angular Observable:无法读取 Subscribe 中的属性 Length

问题描述 投票:0回答:1

我最近开始使用 Angular 进行开发,并且仍处于学习模式。所以,我遇到了这样的困境,我需要访问 Observable 的 .Subscribe 内部数组的“Length”属性;我目前未定义。奇怪,因为我可以看到数组值,但是当调用 Length 时我得到了未定义。

这是我的代码...

category: Observable<Category>;
categorySubject = new Subject<Category>();
categorySubscription: Subscription;


  
  constructor(private db: AngularFirestore) { }

  retreivingItems() {               
    this.fetchCategoryItems("");

    this.category.subscribe((cat) => {
      console.log(cat.properties); // Here I can see all the values of properties; properties is an array
      console.log(cat.properties.length); // Here I get undefined...
    });                        
    
  }


  fetchCategoryItems(category: string) {
    // Get data from firebase
    
    this.category = this.db
    .collection('category')
    .doc("FBonVeV3RqZVn6DwanCr")
    .get()
    .pipe(      
      map(doc => {                
        const data: any = doc.data() as Observable<Category>;
          return {  
            id: doc.id,
            ...data as Category
          }
      })
    )   

code

我也尝试过使用Subject来包装Observable,但我仍然没有定义。

我的猜测是,在订阅上,类别值尚未完成收集所有流数据......那么我该如何实现这一点?

输出:array output

angular rxjs angular2-observables
1个回答
0
投票

首先要明确一些事情:

  1. 当您“订阅”“Observables”时,它会发出数据。当您调用
    db.collection().doc().get()
    时,您基本上“准备”可观察量以发出数据。
  2. 在未来任何时候“完成”的可观察对象(即网络调用),都会立即完成。所以你不需要“取消订阅”那些可观察量。

现在,在您的代码中,您已定义

fetchCategoryItems
将可观察量存储在
category
属性中,这看起来没有必要。由于您正在调用 Firestore 数据库,因此这是一个网络调用,并且在成功响应后立即完成。因此,您可以修改相关类(假设它是服务提供商),如下所示:

@Injectable({ providedIn: 'root' })
export class CategoryService {
  constructor(private readonly db: AngularFirestore) {}
  fetchItems(category: string) {
    return this.db.collection('category').doc(category).get().pipe(map((doc) => ({ id: doc.id, ...doc.data() })));
  }
}

注意我们如何将其设置为从

fetchItems
方法返回可观察值。现在剩下的就是订阅这个 observable 并获取数据。在组件文件中,您可以执行以下操作:

@Component({ /* ... */ })
export class CategoryComponent {
  constructor(private readonly categoryService: CategoryService) {}
  onFetch() {
    this.categoryService.fetchItems().subscribe((items) => {
      console.log(items.properties); // not `undefined`
      console.log(items.properties.length); // it should be `4` according to your question
    });
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.