Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
Why am I unable to access class properties inside of a passed function of an Angular component?

I am using HTML 5 geolocation inside an Angular component:

...
    export class AngularComponent {
    ...
        constructor(private db: DatabaseService) {}

        // this function is assigned to an HTML button
        logCoords(message, action) {
        navigator.geolocation.getCurrentPosition(this.success, this.error, this.options);
        }

        success(pos) {
            function time() {
            ...
            }
            var crd = pos.coords;
            var lat = crd.latitude
            var long = crd.longitude

            let newCoordinates = {'lat': lat, 'long':long, 'time': time}
            this.db.addLocation(newCoordinates)
        }
    ...
    }
...

I want to store the result of the getCurrentPosition Method inside indexed db using an Angular service but I am unable to access any properties of the component class (this.db is null).

Why I am unable to access this.db inside the success function and how I might be able to work around this?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Because you lose the context this when passing the method as a callback. You can fix this by multiple ways:

logCoords(message, action) {
    // bind context
    navigator.geolocation.getCurrentPosition(this.success.bind(this), this.error.bind(this), this.options);
}

or

logCoords(message, action) {
    navigator.geolocation.getCurrentPosition(this.success, this.error, this.options);

    success = (pos) => {} // <= arrow function
    error = () => {}      // <= arrow function
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Issue is with the below line:

navigator.geolocation.getCurrentPosition(this.success, this.error, this.options);

In above line, you are just passing this.success as callback without setting context to it. So in this case as per javascript principles, this would always refer to window object while you are expecting component reference.
To fix this, you have to set the context (component instance) before passing this.success and for that purpose javascript provided bind() function.

Try below code (very simple fix) -

navigator.geolocation.getCurrentPosition(this.success.bind(this), this.error.bind(this), this.options);

For more details around bind() function refer below link -

https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_objects/Function/bind

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda