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
});
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.