Javascript 离子2:访问主页';来自popover回调的s服务
我在angularJs上已经有一段时间了,我刚换到Angular2。我从一个页面调用一个popover,当从popover中选择一个项目时,我应该从api中获取一些数据。我遇到的问题是,当我使用“this”时,它不再引用供应商上下文,因此我无法访问VendorServices函数。有没有一种方法可以引用父类(调用popover的页面)以便获取它的所有变量Javascript 离子2:访问主页';来自popover回调的s服务,javascript,angular,typescript,ionic2,this,Javascript,Angular,Typescript,Ionic2,This,我在angularJs上已经有一段时间了,我刚换到Angular2。我从一个页面调用一个popover,当从popover中选择一个项目时,我应该从api中获取一些数据。我遇到的问题是,当我使用“this”时,它不再引用供应商上下文,因此我无法访问VendorServices函数。有没有一种方法可以引用父类(调用popover的页面)以便获取它的所有变量 import { Component } from '@angular/core'; import { VendorService} from
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
});
}
这是我得到的错误如果你像那样使用函数(位置){
,那么这个
函数的封闭范围将是函数“实例”。你可以像
(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
showLocationsDropdown(事件){
控制台日志(“位置”);
var self=this;//希望您能以反对票接受答案
?@digiwebguy