0

How to use injected service in listener? In ngOnInit ofcourse it works. But i cant use it in listener.

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../shared/auth.service';

@Component({
  selector: 'mmm-face-id',
  templateUrl: './face-id.component.html',
  styleUrls: ['./face-id.component.css']
})
export class FaceIdComponent implements OnInit {

  constructor(public authService: AuthService) { } // <- Service

  ngOnInit() {
    console.log(this.authService); // <- Everything is fine

    window.addEventListener("message", this.receiveMessage, false);
  }

  receiveMessage(event) {
    console.log(this.authService); // <- Not working. AuthService is null.

    // ...
  }

}
  • Do you still get the error if you change `public authService` to `private authService` in the constructor? – Jeremy Jun 29 '20 at 18:34
  • yes. it is still undefined – Mate Gvenetadze Jun 29 '20 at 18:36
  • What are you seeing in the console onInit? – Jeremy Jun 29 '20 at 18:38
  • Looks like a scoping issue. Can you try this.receiveMessage.bind(this) ? – MikeOne Jun 29 '20 at 18:50
  • Try setting the handler with an arrow function: `window.addEventListener("message", (e) => { this.receiveMessage(e); }, false);`., or define the callback as an arrow function: `receiveMessage = (event) => { ... }`. Or use `this.receiveMessage.bind(this)` as suggested by @MikeOne. – ConnorsFan Jun 29 '20 at 18:53

0 Answers0