简体   繁体   中英

Type 'Subscription' is not assignable to type 'Observable<Exercise[]>'

I use

Angular CLI: 6.0.8

Node: 8.11.3

I just learned Udemy - Angular (Full App) with Angular Material, Angularfire & NgRx. Up on lesson 72 Listening to Value Changes (of_Firestore) I have an error

 export class NewTrainingComponent implements OnInit { exercises: Observable<Exercise[]>; constructor( private trainingService: TrainingService, private db: AngularFirestore) { } ngOnInit() { this.exercises = this.db .collection('availableExercises') .snapshotChanges() .pipe( map(docArray => { return docArray.map(doc => { return { id: doc.payload.doc.id, name: doc.payload.doc.data().name, duration: doc.payload.doc.data().duration, calories: doc.payload.doc.data().calories }; }); }) ).subscribe(result => { console.log(result); }); } onStartTraining(form: NgForm) { this.trainingService.startExercise(form.value.exercise); } } 

error TS2322: Type 'Subscription' is not assignable to type 'Observable'.

error TS2339: Property 'name' does not exist on type '{}'.

error TS2339: Property 'duration' does not exist on type '{}'.

error TS2339: Property 'calories' does not exist on type '{}'.

The error message is very obvious. The exercises is a type of Observable as you have defined:

exercises: Observable<Exercise[]>;

But you assign it to a subscription in your ngOnInit() method.

Your ngOnInit() method should be like the following (do not make the assignment to exercises ):

ngOnInit() {
    this.db
      .collection('availableExercises')
      .snapshotChanges()
      .pipe(
          map(docArray => {
          return docArray.map(doc => {
            return {
              id: doc.payload.doc.id,
              name: doc.payload.doc.data().name,
              duration: doc.payload.doc.data().duration,
              calories: doc.payload.doc.data().calories
            };
          });
        })
      ).subscribe(result => {
        console.log(result);
      });
  }

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