1

I've been on angularJs for a while now and I just switched over to angular 2. I'm calling a popover from a page and when an item is selected from the popover, I'm supposed to get some data from an api. The problem I'm having is, when I use 'this', it no longer references the Vendor context so I'm unable to access the VendorServices functions. Is there a way to reference the parent class(the page calling the popover) so I get all it's 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 is the function that handles 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.getVendorsByLocationId(location.id).subscribe(
        this.vendorService.getVendors().subscribe(
          results=>{
            console.log(results);
            this.vendors = results;
          }
        );
      }
    });
    popover.present({
      ev:event
    });
  }

This is the error I getenter image description here

1 Answer 1

2

If you use function(location){ like that then the enclosing scope of the this inside the function will be the functions "instance". You can do something like (location)=>{ to access the lexical this

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

or assign the lexical this to a variable (like self) the old way and use that variable if you don't want to lose the this inside 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
1
  • 1
    Hope you can accept the answer with upvote no? @digiwebguy
    – Sampath
    Commented Mar 26, 2017 at 9:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.