0

I am calling a method in angular but I am getting this error :

TypeError: this.saveCoordinates is not a function

Could you please help me to understand ? This is the code :

export class AppComponent {

  constructor( public http: HttpClient) {
   }

  public saveCoordinates(){
    ///post request here 
    this.http.post<any>('http://localhost:8080/api/tutorials', {
        "title":lat,
        "description":ling
        }).subscribe(data => {
       console.log(data)
    })
    ///post request here
      }
  ngOnInit() {
     map.on('click', function(e) {
      this.saveCoordinates()
        });
  }

}
CoderTn
  • 985
  • 2
  • 22
  • 49
  • 2
    Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback). More specifically, [this answer](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback/38931751#38931751) using arrow functions. – R. Richards Nov 12 '20 at 13:11
  • You forgot to add lat and ling when you call your function – Juany Nov 12 '20 at 13:13
  • @Juany still having the same error even after adding it – CoderTn Nov 12 '20 at 13:16
  • @R.Richards i already checked it and removed this identifier but still having the same error – CoderTn Nov 12 '20 at 13:17
  • replace ngOnInit() { map.on('click', function(e) { this.saveCoordinates() }); } with ngOnInit() { var self = this; map.on('click', function(e) { self.saveCoordinates() }); } because on click callback this represent different scope – Shahid Ahmad Nov 12 '20 at 13:21
  • @ShahidAhmad please add you code as an answer it's working and I will approve it , thanks – CoderTn Nov 12 '20 at 13:26
  • in ngonit you are listening for an event and in event callback this reference to different scope due to which it gives you this type errors so you need to save the reference of this in a variable before this event binding and then instead of this used that variable to call that function on it to know about the scope of this in different scenario please check the below link https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback – Shahid Ahmad Nov 12 '20 at 13:31
  • @يومياتتلــميذتونــسي question is marked duplicate that's why I can't add an answer to your question – Shahid Ahmad Nov 12 '20 at 13:44

0 Answers0