繁体   English   中英

Ionic 2:通过弹出式回调访问主页的服务

[英]Ionic 2: access main page's services from popover callback

我使用angularJs已经有一段时间了,我刚刚切换到angular2。我正在从页面调用弹出窗口,当从弹出窗口中选择一个项目时,我应该从api中获取一些数据。 我遇到的问题是,当我使用“ this”时,它不再引用Vendor上下文,因此无法访问VendorServices函数。 有没有一种方法可以引用父类(调用弹出窗口的页面),以便获取所有变量?

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

  }

这是处理弹出框的函数:

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

这是我得到的错误 在此处输入图片说明

如果像这样使用function(location){ ,则this函数内部this的封闭范围将是函数“实例”。 你可以这样做(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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM