在Angular中使用take运算符时出错

时间:2018-03-26 15:56:03

标签: angular rxjs

我正在使用Angular 5.

我试图使用rxjs take运算符,但得到以下错误(位于函数1中): ERROR TypeError:userDoc.collection(...)。doc(...)。snapshotChanges(...)。take不是函数

当位于功能2时: ERROR TypeError:this.getMyMeasurement(...)。take不是函数

Import section:
import { Injectable, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { take } 'rxjs/add/operator/take'; // Don't think this is necessary, since Observable is imported
import { Subscription } from 'rxjs/Subscription';

import {
  AngularFirestore,
  AngularFirestoreCollection,
  AngularFirestoreDocument
} from 'angularfire2/firestore';

import { AuthService } from '../../users/services/auth.service';
import { UserdbService } from '../../users/services/userdb.service';
import { SelectionModel } from '@angular/cdk/collections';

import { User } from './../../users/models/User';
import { MeasurementLibrary } from '../../library/models/MeasurementLibrary';
import { MyMeasurement } from '../models/MyMeasurement';
import { MyMeasure } from '../models/MyMeasure';

import * as collection from '../../common/collections';
.
.
.
Function 1:
  getMyMeasurement(id: string): Observable<MyMeasurement> {
    const email = this.authService.getLoginUserid();
    const userDoc = this.afs.doc<User>(`users/${email}`);
    this.$measurement = userDoc
      .collection<MyMeasurement>(collection.MY_MEASUREMENT)
      .doc(id)
      .snapshotChanges()
      // Have tried here too take(1)
      .map(action => {
        if (action.payload.exists === false) {
          return null;
        } else {
          const data = action.payload.data() as MyMeasurement;
          data.id = action.payload.id;
          return data;
        }
      });

    return this.$measurement;
  }

Function 2:
  updateDateAndMeasure(id: string) {
    this._measurementSubscription2 = this.getMyMeasurement(id)
      .take(1) 
      .subscribe(myMeasurement => {
        this.myMeasurement = myMeasurement as MyMeasurement;

        if (!this.myMeasurement.firstMeasurement) {
          this.myMeasurement.firstMeasurement = new Date();
        }

        this.myMeasurement.numberOfMeasures =
          this.myMeasurement.numberOfMeasures + 1;

        const email = this.authService.getLoginUserid();
        const measurementDoc = this.afs.doc<User>(
          collection.USERS + `/${email}`
        );
        measurementDoc
          .collection<MyMeasurement>(collection.MY_MEASUREMENT)
          .doc(id)
          .update(this.myMeasurement);
      });
  }

1 个答案:

答案 0 :(得分:0)

正如@martin所说,你错误地导入了操作符。它是:

import 'rxjs/add/operator/take'

这是必要的,因为虽然您导入Observable,但默认情况下它不包含运算符(因此只将您使用的运算符添加到应用程序的最终包中)。您没有真正导入任何内容,但只需添加该导入,take方法就会添加到Observable.prototype,因此您可以使用它。