Accessing services from the main page's popover callback in Ionic 2 is essential for enhancing user interaction and

After spending some time working with angularJs, I recently made the switch to angular 2. I am facing an issue with calling a popover from a page and fetching data from an API when an item is selected from the popover. The problem arises when I try to access the VendorServices functions using 'this', as it no longer references the Vendor context. Is there a way to reference the parent class (the page calling the popover) to access all its variables?

import { Component } from '@angular/core';
import { VendorService} from '../vendors/services'
import { NavController, NavParams } from 'ionic-angular';
import { Meals } from '../meals/meals';
import { PopoverController } from 'ionic-angular';
import { LocationsPopover } from '../locations-popover/locations-popover';

@Component({
  selector: 'vendors',
  templateUrl: 'vendors.html'
})
export class Vendors {

  mealsPage = Meals;
  public locationName: string;
  vendors: any;
  selectedLocation:String;


  constructor(public navCtrl: NavController, public params:NavParams, private vendorService:VendorService, public popoverController: PopoverController) {
    this.locationName = params.get('location');

  }

This function is responsible for handling the popover:

  showLocationsDropdown(event){
    console.log("locations");
    let popover = this.popoverController.create(LocationsPopover,{
      cb:function(location){
        this.selectedLocation = location.location_name;
        console.log("selectedLocation", location.location_name);
        this.vendorService.getVendors().subscribe(
          results=>{
            console.log(results);
            this.vendors = results;
          }
        );
      }
    });
    popover.present({
      ev:event
    });
  }

Here is the error message I am encountering: https://i.sstatic.net/9noy1.png

Answer №1

By utilizing function(location){ in this manner, the enclosing scope of the this within the function will pertain to the functions "instance". If you wish to access the lexical this, you can utilize (location)=>{

showLocationsDropdown(event){
        console.log("locations");
        let popover = this.popoverController.create(LocationsPopover,{
          cb:(location)=>{
            this.selectedLocation = location.location_name;

Alternatively, you can assign the lexical this to a variable (such as self) in the traditional way and use that variable if you prefer not to lose the this within the function

showLocationsDropdown(event){
    console.log("locations");
    var self = this; //<-- assign here
    let popover = this.popoverController.create(LocationsPopover,{
      cb:function(location){
        self.selectedLocation = location.location_name; //<-- use here

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

Tips for saving a JavaScript object into a JSON file

Let's discuss how to save the following data: myJSONtable into a JSON file using the following method: fs.writeFile('./users.json', JSON.stringify(myJSONtable, null, 4), 'utf-8', function (err) { if (err) throw err ...

Discover the secret to smoothly scrolling to an element in ReactJs

Currently, I am in the process of constructing a Single Page Application (SPA) using React and one key functionality I need to implement is navigation that scrolls to specific sections on the page when clicked. This behavior is similar to how anchor tags w ...

Create a combined string from a structure resembling a tree

In my web application, I have a type that defines the different routes available: interface IRoute { readonly path: string, readonly children?: IRoute[] } I want to create a union type containing all possible paths based on an IRoute object. Let&apos ...

Can an AJAX upload progress bar be implemented in Internet Explorer without using Flash?

I've been searching for solutions to upload files without using flash, but all of them either require flash or lack a progress bar on IE (7-8). I couldn't find any mention of an "progress" event in the MSDN documentation for XMLHTTPRequest. Is i ...

Using Paper Checkbox to Toggle the Visibility of a Div in Polymer

Having experience with Meteor, I typically used JQuery to toggle the display of a div along with paper-checkbox: HTML: <paper-checkbox name="remoteLocation" id="remote-chk" checked>Remote Location</paper-checkbox> <div id="autoUpdate" clas ...

Ways to delete a document from Mongodb depends on the existence of a more recent document

Is there a way to automatically delete previous database insertions in my meteor web app whenever a new document is inserted? I've attempted the following code, but it hasn't been successful: if(SearchLobby.find({profile: Meteor.userId()}).count ...

Exploring TypeScript: Ensuring Compatibility of Types

Given two sets of TypeScript type definitions in string format: Set A: { a: string b: number } Set B: { a: string } Is there a way to programmatically determine if these two sets are compatible? In other words, can we assign variables defi ...

Monitor changes in the DOM using AngularJS

In my project, I have a form that is initially hidden using ng-if to remove it from the DOM. Later on, I show the form and attempt to submit the button within it using the following code: <form action="post.php" ng-if="success == true" method="post"&g ...

Unable to retrieve the third attribute of a Class using Angular2's toString method

Here is the code snippet I am working with: import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Hello {{name}}</h1> <p><strong>Email:</strong> {{email}}< ...

Running PHP scripts within an Angular2 CLI application

I'm currently working on an Angular 2 app using Angular CLI, but I've noticed that the PHP files are not being compiled correctly. I'm curious if the server that is included with Angular CLI supports PHP. If not, do you have any recommendati ...

Can you please tell me the name of the ??= operator in Typescript?

The Lit Element repository contains a function called range that utilizes the ??= operator. This operator resembles the nullish coalescing operator but with an equal sign. Do you know what this specific operator is called? Below is the complete code snipp ...

Guide to shutting down Bootstrap 5 modal using React

Incorporating bootstrap 5 with react in my project without installation, I am utilizing CDN links to integrate bootstrap elements into the DOM. The challenge arises when attempting to close the bootstrap modal after data is updated. Despite trying to uti ...

Encountering difficulties in linking socket.io node server to react frontend. Receiving a "404 (Not Found) error for "POST http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MoHNIJT"

I have set up a frontend using React and a backend with Express Node.js. I am utilizing socket.io for communication between the client and server. Upon loading the React page, I encounter an error message that repeats every second: Failed to load resourc ...

Angular: Radio button groups are not responding correctly when populated within a loop using ng-repeat

My goal is to populate multiple sets of radio buttons in a loop by combining the group name and index to ensure each set is uniquely grouped. However, I am facing an issue where only the last group in the loop has a checked radio button, while all other gr ...

Confirm the Keycloak token by checking it against two separate URLs

In my system, I have a setup based on Docker compose with back-end and front-end components. The back-end is developed using Python Flask and runs in multiple docker containers, while the front-end is coded in TypeScript with Angular. Communication between ...

Pressing the submit button will not successfully forward the form

I've encountered an issue with my submit buttons - when I click on them, nothing happens. They were functioning properly before, but now they seem to be unresponsive. What could be causing this problem? <form id="contact" name="updateorder" acti ...

Dealing with 401 Unauthorized error and CORS issues in Angular POST requests to a .NET Core Web Api

My front-end and back-end projects are separate, using Angular for the front-end and .NET Core WEB Api for the back-end. I have successfully set up CORS and windows AD authentication. While GET calls work fine, I am experiencing issues with POST requests. ...

Creating transclusion templates in a compiled format

<div overlay config="overlayConfig"> <div class="dismiss-buttons"> <button class="btn btn-default" ng-click="subscriptions()">Save</button> </div> </div> app.directive("Overlay", ["$timeout", "$compile ...

Leveraging gzip files in production with Angular 2

I have recently implemented angular-cli to compile my application. After running `ng build --prod`, I noticed that the gzip bundle files are generated, but the index.html is still referencing the full-sized files. I attempted using `ng build --prod --aot ...

In PhantomJS, where is the location of the "exports" definition?

Consider the following code snippet from fs.js: exports.write = function (path, content, modeOrOpts) { var opts = modeOrOptsToOpts(modeOrOpts); // ensure we open for writing if ( typeof opts.mode !== 'string' ) { opts.mode = ...