2017-03-26 3 views
1

저는 한동안 angularJs에 있었고 방금 2 번으로 바꿨습니다. 나는 페이지에서 팝업을 호출하고 팝 오버에서 항목이 선택되었을 때 , 나는 API에서 데이터를 얻으려고합니다. 내가 가지고있는 문제는 'this'를 사용할 때 VendorServices 함수에 액세스 할 수 없으므로 더 이상 공급 업체 컨텍스트를 참조하지 않는다는 것입니다. 부모 클래스 (popover를 호출하는 페이지)를 참조하여 모든 변수를 얻을 수있는 방법이 있습니까? 이오닉 2 : 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 
    }); 
    } 

이것은 당신이 함수 내에서 그 같은 this의 둘러싸 범위를 function(location){를 사용하는 경우 오류가 나는 enter image description here

답변

2

를 얻을 수있다 함수 "인스턴스"가 될 것입니다. (location)=>{는 어휘 this

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

에 액세스하거나 변수에 (같은 self)을 어휘 this를 할당 옛날 방식을 그 변수를 사용하는 것처럼 당신이 내부의 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 
+0

감사합니다. 이것으로 해결했습니다. – digiwebguy

+1

당신이'upvote no'와 함께 대답을 수락 할 수 있기를 바라십니까? @digiwebguy – Sampath