【问题标题】:Why am I obtaining these two errors trying to subscrive an Angular service method that retrieve data from Firestore database?为什么我在尝试订阅从 Firestore 数据库中检索数据的 Angular 服务方法时遇到这两个错误?
【发布时间】:2025-11-22 12:05:01
【问题描述】:

我正在学习与 Angular 和 Firestore 数据库相关的课程,但遇到以下两个问题:

在控制器类中,我有这个 ngOnInit() 方法:

ngOnInit() {

this.course = this.route.snapshot.data['course'];
this.lessons = this.coursesService.findLessons(this.course.id)
    .subscribe(
      lessons => this.lessons = lessons
    );

}

如您所见,我正在订阅 coursesService.findLessons() 方法,这是该服务方法的代码:

findLessons(courseIs: string, sortOrder: OrderByDirection = 'asc', 页数 = 0, pageSize = 3): 可观察的 {

return this.db.collection('courses/${courseId}/lessons',
            ref => ref.orderBy('seqNo', sortOrder)
            .limit(pageSize)
            .startAfter(pageNumber * pageSize))
            .snapshotChanges()
            .pipe(
              map(snaps => convertSnaps<Lesson>(snaps)),
              first()
            )

}

在这个服务方法上,Visual Studio Code 在这一行给我一个错误:

sortOrder: OrderByDirection = 'asc',

错误提示:

找不到名称“OrderByDirection”.ts(2304)

在将此服务方法调用到我的控制器 ngOnInit() 方法时,在 this.lessons 上给我一个错误(之前定义为 lessons : 课程[];

Type 'Subscription' is missing the following properties from type 'Lesson[]': length, pop, push, concat, and 26 more.ts(2740)

具体是什么意思?为什么我会收到此错误?我错过了什么?我该如何尝试修复它?

【问题讨论】:

    标签: angular firebase google-cloud-firestore


    【解决方案1】:
    1. ActivatedRoute 中的参数通常是序列化的对象字符串。请检查this.course.id 是否为有效值。

    2. Template literals 必须使用反引号而不是引号括起来。

    替换

    'courses/${courseId}/lessons'
    

    `courses/${courseId}/lessons`
    

    【讨论】: