Unable to retrieve property within a function in Typescript

export class DuyurularPage {
    duyurular: any;
    loading: any;

    constructor(public navCtrl: NavController, public navParams: NavParams, public loadingPage: LoadingController,
        platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {

        this.loading = this.loadingPage.create({
            content: `
            <ion-spinner></ion-spinner>`
        });

        platform.ready().then(() => {
            statusBar.styleDefault();
            splashScreen.hide();

           // Retrieve notification data and assign it to the 'duyurular' variable  
           var notificationOpenedCallback = function (jsonData) {
                this.duyurular = jsonData.notification.payload;
            };

            alert
            window["plugins"].OneSignal
            .startInit("12312412412412", "1231241212")
            .handleNotificationOpened(notificationOpenedCallback)
            .endInit();
        });
    }
}

var notificationOpenedCallback = function...
← Within this function, accessing this.duyurular is not possible.

I need to populate the array (duyurular) with data from a JSON source. How should I proceed?

Answer №1

The reason for the issue is due to the incorrect scope of the function below.

    var notificationOpenedCallback = function(jsonData) {
      this.duyurular = jsonData.notification.payload;
    };

To solve this, you can either change it to a fat arrow function or define the scope outside of this block:

Recommended approach:

    var notificationOpenedCallback = (jsonData) =>  {
      this.duyurular = jsonData.notification.payload;
    };  

Alternative approach using an external scope:

    const self = this;

    var notificationOpenedCallback = function(jsonData) {
      self.duyurular = jsonData.notification.payload;
    };     

When constructing the array, the data will be in the form of a JSON object. Extract the necessary data from the JSON and utilize it to build the array for your component. For further guidance on this, refer to the following question: How to convert JSON object to JavaScript array

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

Error: The value of _This.props is not defined

Hey there, I am new to working with React Native and could really use some assistance with this issue: TypeError: _props.goToScreen is not a function. Any help would be greatly appreciated, thank you in advance! In my Profile.js file, I am trying to click ...

Replacing the yellow autofill background

After much effort, I have finally discovered the ultimate method to remove autofill styling across all browsers: $('input').each(function() { var $this = $(this); $this.after($this.clone()).remove(); }); However, executing t ...

Label positioning for checkboxes

Is there a way to display the checkbox label before the actual checkbox without using the "for" attribute in the label tag? I need to maintain the specific combination of the checkbox and label elements and cannot use nested labels or place other HTML elem ...

Sorting JavaScript Objects By Date

My goal is to arrange my array of objects with date values in descending and ascending order. Here is the code I am using: function comp(a, b) { return new Date(a.jsDate) - new Date(b.jsDate); } function compNewestFirst(a, b) { return new Date(b.jsD ...

bootstrap thumbnail displayed without a border

I have decided to incorporate Bootstrap into my latest project: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS ...

How to sort an array of multiple objects in AngularJS based on a specific property

Having an array of multiple objects: { "option_12": { "id": "0", "name": "6 x 330ml", "price": "0.00" }, "option_14": { "id": 1, "name": "12 x 330ml", "price": "2.00" }, "option_17": { "id": 1, ...

The attempt to execute 'removeChild' on 'Node' was unsuccessful due to an uncaught DOMException

'removeChild' execution failed on 'Node': The specified node is not a child of this element. Whenever I run the code below, an error occurs. Is there a solution to fix this issue? function clickLinks(links) { for(var item in links) ...

Using gulp to compile TypeScript is resulting in a directory being generated that we do not want

My goal is to use Gulp to transpile my .ts files located in the /dev directory, and then move the transpiled .js file to a /build directory. The ideal folder structure I am aiming for is as follows: /dev - index.ts /build - index.js However, the curre ...

Can you propose a different approach to creating the "word stack" that overcomes the limitations of my current method?

I am attempting to convert a set of two radio buttons into a stack of two labels, one blue and one gray, to represent the selected radio button and the unselected one. Clicking on this stack will toggle which label is blue (and consequently which radio but ...

Error message 'Access is Denied' occurs when using Angular.js xhr.open()

Currently, I am developing an angular web application that needs to be compatible with IE10. One of the requirements is to make a cross-domain call to our enterprise salesforce server. When using Chrome (not officially supported but commonly used for devel ...

Step-by-step guide on parsing JSON data on a Windows phone device

Can someone assist me with parsing this JSON data using JSON.net in C#? Here is the JSON Data Below are the results: [{"rescode":0,"policyid":"1","Insuredid":"2606"}, {"rescode":0,"policyid":"2","Insuredid":"2607"}, {"rescode":0,"policyid":"3","Insuredid ...

Ways to customize pixel scrolling on page reload or through the use of a hyperlink to a specific tab in a page

I have implemented a Bootstrap panel using the following code: <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a class="nav-link active" data-toggle="tab&qu ...

Adjust the div's height to 0

I need to dynamically set the height of a div element with a height of 34px to 0px. However, this div does not have a specific class or ID, so I can't use traditional DOM manipulation methods like .getElementById(), .getElementByClassName, or .getElem ...

Can one utilize Javascript/Angular to listen for a 'request sent' event trigger?

Is there a method in a Javascript/Angular application to intercept a 'request-sent' event triggered by the browser right after the request is sent out? Our goal is to manage and prioritize the order of outgoing requests, potentially sending each ...

Challenges in retrieving information from a two-dimensional JSON dataset

I am encountering an issue with a nested JSON structure. JSON: [{"id":"15", "rand_key":"", "landlord_name":"Shah", "property_req_1":{ "lead_req_id":"", "lead_id":"0", "category_id":"1", "region_id":"1", "area_location_id":"17", ...

Dynamically insert a new row into an HTML table using AJAX and refresh the table with .load method

I am facing an issue with my HTML table that loads data dynamically through a PHP snippet containing SQL queries. There is a Select option and a button on the table to add a new row, which triggers an AJAX procedure to send the data to PHP for insertion in ...

Separating an Array Subset in JavaScript/jQuery

I need to filter a specific part of a javascript array containing objects by a particular condition, such as: object.property == 2 Instead of manually building a new array with the matching items, I am curious if there is a shortcut for this process. ...

The call to the hook is invalid. In order to use hooks, they must be called within the body of a function component in

So, in my upcoming application, I am incorporating the react-google-one-tap-login library which features the useGoogleOneTapLogin hooks that need to be invoked within a React component. However, when I attempt to use it in this manner: func() { useGoogle ...

Tips for troubleshooting common network errors in Volley

When attempting to access this function through WiFi, it works fine. However, when using a mobile network, I encounter the following error: D/Volley: [3641] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] 0x95bac5ee NORMAL 14> * 2020-0 ...

Creating a video game HUD effect using JavaScript and HTML5

In an attempt to recreate a video game HUD using HTML5, I have styled a div with CSS properties to resemble a game overlay. When a navigation link is clicked, the div should transition from a hidden state (display:none), then flash twice rapidly before fad ...