moff / angular2-flash-messages

Angular 2 flash messages module
52 stars 21 forks source link

TypeError: Cannot read property 'flashMessagesService' of undefined #35

Closed Adlesa closed 6 years ago

Adlesa commented 6 years ago

I cant get my head around this problem.

This is the Code:

import { Component, OnInit } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { FlashMessagesService } from 'angular2-flash-messages';

@Component({
  selector: 'app-add-client',
  templateUrl: './add-client.component.html',
  styleUrls: ['./add-client.component.css']
})
export class AddClientComponent implements OnInit {

  companyName: string;
  companyCvr: string;

  clientCollection: AngularFirestoreCollection<any> = this.afs.collection('client');

  constructor(
    private afs: AngularFirestore,
    private flashMessagesService: FlashMessagesService) { 

    }

  ngOnInit() {

  }

  onSubmit(){
    // Get the ID for companyCvr = this.companyCvr
    this.clientCollection.doc(this.companyCvr).set({
      companyName: this.companyName,
      companyCvr: this.companyCvr
    })
    .then(function() {
      console.log("Document successfully written!");
      this.flashMessagesService.show('Kunden er nu oprettet', { cssClass: 'alert alert-success', timeout: 2000 });
    })
    .catch(function(error) {
        console.error("Error writing document: ", error);
    });
  }

}

If I move the: this.flashMessagesService.show('Kunden er nu oprettet', { cssClass: 'alert alert-success', timeout: 2000 }); outside the .then block it runs fine but inside the .then I get this error: Error writing document: TypeError: Cannot read property 'flashMessagesService' of undefined

Any suggestions?

moff commented 6 years ago

@Adlesa that's because inside of .then you use anonymous function, therefore when you call this.something inside its body you actually make a call to the function context - not a class. You should use something like:

// put it inside of onSubmit() method
var flashMessagesService = this.flashMessagesService;

// and call it inside your .then function
flashMessagesService.show('Kunden er nu oprettet', { cssClass: 'alert alert-success', timeout: 2000 });
Adlesa commented 6 years ago

@moff You are completely right.

Thank you very much - it works perfectly now.

LewisMorgans commented 5 years ago

I am having the same problem, but your solution is not working for me.

this.currentUser.updatePassword(this.pF.passwordOne.value) .then(() => { this.flashMessages.show('Password Updated.', { cssClass: 'alert-success', timeout: 2000 }); })

Producing the error: ERROR TypeError: Cannot read property 'flashMessages' of undefined

Do you have any other solutions or thoughts on the issue? It's been imported, and instantiated in the constructor as instructed. What's very odd is that it works in a different place with the same code...

Any help much appreciated.