Encountering an issue with undefined properties in Typescript Angular 5, specifically unable to read the

Encountering an issue while utilizing Angular 5 Services, looking for assistance in identifying what's wrong with the code below

Referenced various questions but none provided a solution

  1. Question 1
  2. Question 2
  3. Question 3

The aim is to initialize a value within the class and utilize it in a method

Even though the url value is defined in the class, encountering an error

Cannot read property 'url' of undefined
at console.log(this.url);

@Injectable()
export class OwnService {

    public accessTokenvalue = '';
    public url = 'https://www.someurl.com/id=';
    constructor(private hp: HelpService) {
    }

    public gethpPhotos() {
        this.hp.login()
            .then(function (response: LoginResponse) {
                console.log(response);
                console.log(this.url);

            })
            .catch((error: any) => console.error(error));
    }
}

Answer №1

To solve this issue, simply switch out function (response: Response) with an arrow function. Regular function declarations create their own scope, which can cause issues with the reference to this. Arrow functions will maintain the context of this.

.then((response: LoginResponse) => {
     console.log(response);
     console.log(this.url);
})

Answer №2

To effectively handle this situation, consider utilizing the surrounding context in which the 'url' is present:

public retrievePhotos() {
       var that = this; // reference to outer context

        this.hp.login()
            .then(function (response: LoginResponse) {
                console.log(response);
                console.log(that.url); // Updated to refer to that.url from the outer context

            })
            .catch((error: any) => console.error(error));
    }

Answer №3

When looking at your code, "this" points to the context of the http request. To be able to reach the component variable, make sure to utilize arrow functions.

this.hp.login()
.then((response: LoginResponse) => {
        this.answerList = response;
         console.log(this.url);
)

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

Is it possible to utilize an array of numbers as a data source in ng2-smart table?

Hey there, I'm currently facing an issue with populating ng2-smart-table with an array of numbers. When I try to display the table, all I see is 6 empty rows like this: https://i.stack.imgur.com/DZJjq.png Here's the code for the table: <ng2- ...

Access the plugin object from a Vue.js 2 component using typescript

I devised a plugin object to handle the regular expressions used in my application in a more global manner. Here's an example of how it looks: import Vue from "vue"; Vue.prototype.$regex = { //isEmail function implementation goes here } ...

Iterate and combine a list of HTTP observables using Typescript

I have a collection of properties that need to be included in a larger mergeMap operation. this.customFeedsService.postNewSocialMediaFeed(this.newFeed) .mergeMap( newFeed => this.customFeedsService.postFeedProperties( newFeed.Id, this.feedP ...

Incorporating angular2 with fullpagejs requires loading fullpage js after successfully binding data within Angular

Trying to incorporate fullpage js features into Angular2 has been a challenge for me. The issue arises when I have multiple sections on my page, with one section having child sections generated through JSON data using template binding. For example, the "se ...

What is the proper way to reference the newly created type?

I came up with a solution to create a custom type that I can easily use without the need to constantly call useSession(), as it needs to be a client-side component. However, whenever I try to access this custom type, it always returns undefined (if I try t ...

The sign out option fails to erase the data stored in Local Storage

After implementing a login feature that stores a token in local storage, I encountered an issue with the logout button. The intention was for the button to delete the token from local storage and set the user to null upon clicking it. However, this functio ...

The absence of the @Injectable annotation is causing an issue when importing a JSON

I am currently in the process of integrating a JSON file into my service by using a @inject() tag within the constructor. Below is the code snippet I am working with. DependencyInjectionContainer.ts import { Container, decorate, injectable } from "invers ...

SVG is not incorporated in the Typescript build

I'm facing an issue where my build using tsc --project tsconfig.dist.json (refer to the file below) does not include the assets (.svg files) that are imported and used in the code. How can I make TypeScript include these assets in the build? Some con ...

Send empty object using FormBuilder

When retrieving an object from a backend API service like this: data: {firstName:'pepe',lastName:'test', address = {street: 'Cervantes', city:'Villajoyosa'} } or data: {firstName:'pepe',lastName:'test ...

Updating the state in React is causing significant delays

In my React project, I am utilizing the pdf-lib (JS library) for some intensive tasks using async/await. My goal is to update a progress bar by modifying the state. However, when I use setState within a setTimeout, the state changes are not reflected unt ...

Enhance user experience with Bootstrap by automatically adding a frame around a card upon clicking

Hello everyone! I am a beginner in the Angular/Web Development world and I am currently working on improving my HTML/CSS skills. While using Bootstrap in my Angular project, I ran into a challenge that I couldn't figure out on my own. I have implement ...

Exploring the terrain of observable data

Understanding how to filter an observable is really challenging for me right now. I have a gadget {name: string, description: string} I possess an observable collection of gadgets [{},{},{}] My goal is to iterate through my observable collection of ga ...

Generate a TemplateRef and place it into the template of the component

Inquiring about Angular 5.0.2 After reviewing the example provided on NgTemplateOutlet at https://angular.io/api/common/NgTemplateOutlet I am eager to discover if there is a method to dynamically generate a TemplateRef and then insert it into the componen ...

Utilizing a Storybook default export (without a specific name) along with a template rather than a component

Utilizing storybook, you have the ability to create a named story template by: export default { title: 'My Component', } as Meta; export const Default: Story<any> = () => ({ template: ` <p>My story</p> ` }); Displa ...

What is the best way to transform an array of objects into a nested array through shuffling

I am dealing with a diverse array of objects, each structured in a specific way: data = [ { content: { ..., depth: 1 }, subContent: [] }, { content: { ..., depth: 2 ...

The webpage at 'https://abcd.ac.in/' has been declined to be displayed in a frame due to the 'X-Frame-Options' being set to 'sameorigin'

When attempting to load a website within an iframe, I encountered an error in the console stating "Refused to display 'https://abcd.ac.in/' in a frame because it set 'X-Frame-Options' to 'sameorigin'. Despite trying other alte ...

Configuring routes for Angular4 router is a vital step in creating a

Issue: I am currently setting up routes for my application, aiming to structure the URL as https://localhost:4200/hero=id, where the 'id' will be dynamically selected. However, this setup is not functioning as expected. If I attempt to use a URL ...

Angular 2 error: Unhandled Promise rejection stating that the template has parsing errors - the element 'login' is not recognized

I am currently attempting to implement Firebase Authentication login for an Angular2 project. However, I encountered the following error: Unhandled Promise rejection: Template parse errors: 'login' is not a known element: 1. If 'login&apos ...

Ever tried asynchronous iteration with promises?

I have a specific code snippet that I am working on, which involves registering multiple socketio namespaces. Certain aspects of the functionality rely on database calls using sequelize, hence requiring the use of promises. In this scenario, I intend for t ...

What is the best way to activate an <ion-datetime> with an <ion-button>?

Im currently attempting to execute the following action: I would like to select only the month and year using the example below: <ion-datetime presentation="month-year"></ion-datetime> However, I do not wish for this label to be vis ...