【发布时间】:2021-09-26 04:23:35
【问题描述】:
/* Services: client-service.ts */
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs';
import { Client } from '../models/Client';
import 'rxjs/add/operator/map';
@Injectable({
providedIn: 'root'
})
export class ClientService {
clientsCollection!: AngularFirestoreCollection<Client>;
clientDoc!: AngularFirestoreDocument<Client>;
clients!: Observable<Client>[];
client!: Observable<Client>;
constructor(private afs: AngularFirestore) {
this.clientsCollection = this.afs.collection('clients', ref => ref.orderBy('lastName', 'asc'));
}
getClients(): Observable<Client[]> {
// Get clients with the id
this.clients = this.clientsCollection.snapshotChanges().map(changes => {
return changes.map(action => {
const data = action.payload.doc.data() as Client;
data.id = action.payload.doc.id;
return data;
});
});
return this.clients;
}
}
我收到这两个错误:
- “Observable
”类型缺少“Observable[]”类型的以下属性:length、pop、push、concat 等 24 个。 - “Observable[]”类型缺少“Observable
”类型中的以下属性:_isScalar、source、operator、lift 等 5 个。
这是订阅它的组件:
/* the client-component.ts file */
import { Component, OnInit } from '@angular/core';
import { ClientService } from '../../services/client.service';
import { Client } from '../../models/Client';
@Component({
selector: 'app-clients',
templateUrl: './clients.component.html',
styleUrls: ['./clients.component.css']
})
export class ClientsComponent implements OnInit {
/* Properties */
clients!: Client[];
constructor(private clientService: ClientService) { }
ngOnInit(): void {
this.clientService.getClients().subscribe(clients => this.clients = clients);
}
}
【问题讨论】:
-
snapShotChanges 返回什么类型?如果它是一个 observable,那么您在应该订阅时映射不正确。
-
是的,我最初在上面分享的代码是服务文件。我将使用订阅它的组件进行更新。
-
我已根据您的更新提供了建议的解决方案。
-
在这两个区域都放置这个注释,所以希望你能看到它:) 对于第二行,我收到了这个错误:Type 'Observable
' is missing the following properties from type 'Observable[]':长度、pop、push、concat 等 25 个。我还收到一个额外的错误:')'预期。返回 this.clients;我收到了这个错误:(和以前一样):类型'Observable []'缺少来自类型'Observable '的以下属性:_isScalar、source、operator、lift 和另外 5 个. -
我还用我最初错误的精确截图更新了原始问题
标签: angular typescript google-cloud-firestore