我使用angularJs已经有一段时间了,我刚刚切换到了角2,我从一个页面调用了一个弹出器,当一个项从弹出器中被选中时,我应该从一个api中获得一些数据。我遇到的问题是,当我使用“this”时,它不再引用Vendor上下文,因此我无法访问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');
}
这是处理弹出程序的函数:
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
});
}
这就是我所犯的错误
发布于 2017-03-26 01:25:55
如果像那样使用function(location){
,那么函数中的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
https://stackoverflow.com/questions/43027057
复制相似问题