2017-03-26 6 views
1

私はしばらくの間、angularJsにいましたが、私は角度2に切り替えました。私はページからポップオーバーを呼び出しています。 、私はAPIからいくつかのデータを取得するはずです。私が抱えている問題は、「this」を使うとVendorのコンテキストを参照しなくなり、VendorServices関数にアクセスできなくなります。親クラス(Popoverを呼び出すページ)を参照する方法があるので、すべて変数を取得しますか?Ionic 2:ポップオーバーコールバックからのメインページのサービスへのアクセス

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

を取得エラーです関数 "インスタンス"になります。あなたが内部thisを失いたくない場合は、字句this

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

または(selfなど)の変数に字句thisを割り当てるに古いやり方にアクセスし、その変数を使用する (location)=>{ような何かを行うことができます機能

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

関連する問題