Ionic 2:从popover回调访问主页面的服务

时间:2017-03-26 09:22:01

标签: javascript angular typescript ionic2 this

我已经在angularJs上呆了一段时间了,我刚刚切换到了角度2.我从一个页面调用一个弹出窗口,当一个项目从弹出窗口中选出时,我就是应该从api获取一些数据。我遇到的问题是,当我使用'这个'时,它不再引用供应商上下文,因此我无法访问VendorServices功能。有没有办法引用父类(调用popover的页面)所以我得到它的所有变量?

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');

  }

这是处理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
    });
  }

这是我得到的错误enter image description here

1 个答案:

答案 0 :(得分:2)

如果您使用function(location){,那么函数内this的封闭范围将是函数“instance”。你可以做点什么 (location)=>{访问词汇this

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

或者将词汇this分配给旧方式的变量(如self)并使用该变量,如果您不想丢失函数内的this

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