简体   繁体   中英

Why does Angular ask me for these properties, and how can I fix it?

/* 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;
  }

}

I am getting these two errors :

  • Type 'Observable<Client[]>' is missing the following properties from type 'Observable[]': length, pop, push, concat, and 24 more.
  • Type 'Observable[]' is missing the following properties from type 'Observable<Client[]>': _isScalar, source, operator, lift, and 5 more.

Here is the component that is subscribing to it:

/* 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);
  }

}

在此处输入图片说明

You are doing a map on an observable type. This needs to look something like this instead:

getClients(): Observable<Client[]> {
this.clients = this.clientsCollection.snapshotChanges()
  .pipe(
      map(c => {
        return c.map(a => {
          let data = a.payload.doc.data() as Client;
          data.id = a.payload.doc.id;
          return data;
        });
    });
  return this.clients;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM