Error message: The variable "str" is trying to be accessed from null typeScript

Recently I started delving into TypeScript and encountered a problem that's been giving me trouble. Whenever I try to retrieve my location and utilize the Google Maps API to gather street and city information, an error message pops up saying "Cannot read property 'str' of null". It's baffling to me why this is happening. Can anyone provide some guidance?

import { Component, OnInit } from '@angular/core';
import {Http, Response} from '@angular/http';
import 'rxjs/Rx';
import {Observable} from 'rxjs/';

@Component({
  selector: 'app-center',
  templateUrl: './center.component.html',
  styleUrls: ['./center.component.css']
})
export class CenterComponent implements OnInit {
  dataSource: Observable<any>;
  locationInfo: any;
  str: any;
  constructor(public http: Http) {
    this.dataSource = this.http.get('https://maps.googleapis.com/maps/api/geocode/json?'
      + 'latlng=' + this.str + '&key=AIzaSyC2wdo6kMAXpuhwuUa8fM4mCkDy_kZeWKY').map(Response => Response.json());
  }
  ngOnInit() {
  }
  getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(this.showPostion, this.showError);
    }
  }
  showPostion(position) {
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;
    this.str.bind(this);
    this.str = String(latitude + ',' + longitude);
    console.log(this.str);
  }
  showError() {
    console.log('Invalid Address !');
  }
  getData() {
    this.dataSource.subscribe(
      data => this.locationInfo = data
    );
    console.log(this.locationInfo);
  }
}

Answer №1

It is essential to bind callbacks to the current class in TypeScript as it does not automatically handle this for you. A good way to do this is by using

navigator.geolocation.getCurrentPosition(this.showPostion.bind(this), this.showError.bind(this));
. Remember to also omit this.str.bind(this);, as bind should only be used with functions.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the reasons for the inability to send form-data in Postman?

Encountering an issue when trying to send form-data in postman as Sequelize returns an error: value cannot be null However, everything works fine when sending a raw request with JSON. Have tried using body-parser and multer, but no luck. This is my inde ...

Determine the Angular object's type even if it may be undefined

Currently diving into Angular and looking to create a method that can determine if an object is of type Dog (identified by a woof property). This is the code snippet I have put together so far: export class SomeClass { public animal?: Dog | Cat; ... ...

The build script does not execute during the creation of a Node.js and React application in Visual Studio

I am currently following a detailed guide on setting up Visual Studio 2019 to develop a Node.js-React application. The link to the guide can be found here: https://learn.microsoft.com/en-us/visualstudio/javascript/tutorial-nodejs-with-react-and-jsx?view=vs ...

User interface designed for objects containing multiple keys of the same data type along with a distinct key

I have a question that relates to this topic: TypeScript: How to create an interface for an object with many keys of the same type and values of the same type?. My goal is to define an interface for an object that can have multiple optional keys, all of t ...

Running the nestjs build command is impossible without the existence of the node_modules folder

Currently, I am in the process of creating a Nestjs micro-service and everything is going smoothly. To run the build found within the dist folder, I use the command below: node dist/main.js However, I encountered a problem where this command does not exec ...

I am looking to implement tab navigation for page switching in my project, which is built with react-redux and react-router

Explore the Material-UI Tabs component here Currently, I am implementing a React application with Redux. My goal is to utilize a panelTab from Material UI in order to navigate between different React pages. Whenever a tab is clicked, <TabPanel value ...

Turning XSD into TypeScript code

Stumbling upon this tool called CXSD, I was intrigued. The documentation describes cxsd as a streaming XSD parser and XML parser generator designed for Node.js and TypeScript (optional but highly recommended). It seemed like the perfect solution for my ne ...

I want to modify a class in Angular 8 by selecting an element using its ID and adjust the styling of a div

Is it possible to dynamically add and remove classes using getElementById in Angular 8? I need to switch from 'col-md-12' to 'col-md-6' when a user clicks on the details icon. I also want to modify the style of another div by setting d ...

The type 'FormikValues' is deficient in the subsequent properties compared to the type 'Exact<{'

I am currently working on a form with the following structure: import { Field, Form, Formik, FormikProps, FormikValues } from 'formik' import { NextPage } from 'next' import React from 'react' import { useCreateUserMutation } ...

Can type inference be utilized with the `forwardRef` method?

I am having an issue with the Type inference not working with the forwardRef in my component. I understand the reason behind this limitation, but I'm wondering if there is a workaround? https://i.sstatic.net/ZO3gI.png This is what I meant by type in ...

Using the `require('ts-node/register')` method for programmatic implementation in TypeScript

ts-node recommends using require('ts-node/register'). This is also evident in the angular2-webpack-starter Protractor configuration. What exactly does require('ts-node/register') do? Does it modify require to compile TS files, allowing ...

The propagation of onClick events in elements that overlap

Having two divs absolutely positioned overlapping, each containing an onClick handler. The issue is that only the top element's onClick handler fires when clicked. React 17 is being used. Here is some sample code: <div style={{ position: "abs ...

The package import path varies between dynamic code generation and static code generation

I have organized the src directory of my project in the following structure: . ├── config.ts ├── protos │ ├── index.proto │ ├── index.ts │ ├── share │ │ ├── topic.proto │ │ ├── topic_pb. ...

Typescript - Promise resolves prematurely

I have been given a code with three essential parts that cannot be altered: 1. First, there is a call to the getData function, followed by printing the output. getData().then(console.log); 2. The function signature is as follows: async getData(): Promise ...

Why won't Angular 4 create the node_modules folder when using ng new to initialize a new project?

Recently reinstalled Angular and began a new project using ng new. However, I encountered issues when trying to run ng serve after creating the project and changing into its directory. On my Mac Mini, I can simply navigate to the project folder and run ng ...

Is there an improved method for designing a schema?

Having 4 schemas in this example, namely Picture, Video, and Game, where each can have multiple Download instances. While this setup works well when searching downloads from the invoker side (Picture, Video, and Game), it becomes messy with multiple tables ...

A guide on incorporating typings for d3-tip in TypeScript 2.0

Seeking to implement tooltips in my charts using the d3-tip library. After installing typings for d3-tip in Typescript 2.0: npm install @types/d3-tip --save The typings appear in my package.json: "dependencies": { "@types/d3": "^4.7.0", "@types/d3- ...

"Unlock the power of NGXS by leveraging the raw state values

I'm having trouble locating an example in the NGXS documentation that demonstrates how to properly type the state object. Specifically, I am looking for guidance on typing the return value of the snapshot method of Store. For instance: this.store.sn ...

Combining Typescript interfaces to enhance the specificity of a property within an external library's interface

I have encountered a scenario where I am utilizing a function from an external library. This function returns an object with a property typed as number. However, based on my data analysis, I know that this property actually represents an union of 1 | 2. Ho ...

Unraveling TypeScript code expressions

I am seeking clarification on the meaning and practical application of this particular expression. ((identifier:string) => myFunction(identifier))('Hi') myFunction const myFunction = (str:string) => { console.log(str) } The output displ ...