2016-11-24 9 views
1

У меня есть случай, когда я использую компонент в компоненте. Получив доступ к свойствам дочернего компонента через @ViewChild, я становлюсь неопределенным для методов в дочернем компоненте.Угловой 2, дочерний компонент, использующий с ошибками google maps, теряющий контекст

// Parent component 

declare var google: any; 
@Component({ 
    selector: 'app-map', 
    templateUrl: ` 
    <div id="map"></div> 
    <app-context-menu></app-context-menu>`, 
    styleUrls: ['./map.component.css'], 
    providers: [CitiesService], 
}) 

export class MapComponent implements AfterViewInit { 
    @ViewChild(ContextMenuComponent) contextMenu: ContextMenuComponent; 
    user: UserInterface; 
    city: any; 
    map: any; 

    constructor(
    private userStorage: UserStorage, 
    private citiesService: CitiesService, 
    private theMap: TheMap, 
) {} 

    ngAfterViewInit() { 
    this.findUserCityCoords(); 
    } 

    inittializeMap(mapOpts) { 

    let mapProps = { 
     center: new google.maps.LatLng(mapOpts.lat, mapOpts.lng), 
     zoom: mapOpts.zoom, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    let map = new google.maps.Map(document.getElementById('map'), mapProps); 
    let menu = this.contextMenu; 

    map.addListener('rightclick', (e) => { 
     console.log('map', this); 
     console.log('menu', this.contextMenu); 
     this.contextMenu.open(e); 
    }); 
    } 

    findUserCityCoords() { 
    let userCity = this.userStorage.getFromStorage().city; 

    this.citiesService.getCityConfig() 
     .subscribe(cities => { 
     cities.forEach(city => { 
      if (city.name === userCity) this.inittializeMap(city.center); 
     }); 
     }); 
    } 

От этого класса, когда 'map event listener' вызывает 'menu.open (e);' изменения контекста и внутри дочернего компонента, методы дочернего компонента недоступны. Чтобы вызвать метод «this.draw()».

// Child component 
import { Component, OnInit, ElementRef, AfterViewInit } from 

'@angular/core'; 
import { TheMap } from '../../services/mapServices/TheMap'; 
import { Marker } from '../../services/mapServices/marker.service'; 
declare var google: any; 

@Component({ 
    selector: 'app-context-menu', 
    templateUrl: './context-menu.component.html', 
    styleUrls: ['./context-menu.component.css'] 
}) 
export class ContextMenuComponent { 
    overlay; 
    el; 

    constructor(
    private theMap: TheMap, 
    private marker: Marker, 
    private elementRef: ElementRef 
) { 
    this.overlay = new google.maps.OverlayView(); 
    } 

    ngAfterViewInit() {} 

    open(e) { 
    let map = this.theMap.getMap(); 
    this.overlay.set('position', e.latLng); 
    this.overlay.setMap(map); 
    this.draw(); // <---- Here, this.draw() is not a function 
    // So I can access properties from constructor but not this.draw() and other methods of this class 
    }; 

    draw() { 
    // .... 
    } 

Как правильно реализовать карту от Google «RightClick» слушателя событий (возможно, с «связывают»), чтобы использовать компонентные методы моего ребенка. Благодаря

+0

Я думаю, что вам нужно удалить ',' 'после открытой (е) {}' –

ответ

1

Не уверен, что понял вопрос, но () => (функция стрелка) может быть то, что вы ищете

map.addListener('rightclick', (e) => { 
    console.log('map', this); 
    console.log('menu', menu); 
    this.contextMenu.open(e); 
}); 
+0

Я не думаю, что это что-то изменит, потому что OP уже установил 'menu' в' this.contextmenu' вне этой области. – echonax

+1

По крайней мере, это может привести к ответу, который может дать больше понимания, в чем проблема :-) Мне казалось, что он ищет способ сделать эту работу внутри обратного вызова без этого «обходного пути». –

+1

Да, может быть:) – echonax

 Смежные вопросы

  • Нет связанных вопросов^_^