从常见位置调用Angular组件的ngAfterViewInit

时间:2019-01-01 07:00:17

标签: javascript angular twitter-bootstrap angular-lifecycle-hooks

我正在使用引导工具提示。 我想从某个常见的地方为每个组件触发ngAfterViewInit。

公共场所(例如app.module.ts)

<script type="text/javascript">

    // Google mapper initialize function
    function initialize() {

        //To find the current location and add the marker of current location
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
        }
        else { $("#message").html("Geolocation is not supported by this browser."); }

        function showPosition(position) {
            var currentLatLng = position.coords;

            var latlon = "Latitude" + currentLatLng.latitude + "," + "Longitude" + currentLatLng.longitude;

            //Google map options like langitude, latitude and zoom level
            var mapOptions = {
                center: new google.maps.LatLng(currentLatLng.latitude, currentLatLng.longitude),
                zoom: 6,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var directionsService = new google.maps.DirectionsService;
            var directionsDisplay = new google.maps.DirectionsRenderer;
            var geocoder = new google.maps.Geocoder;

            //Get the element of div to show google maps
            var map = new google.maps.Map(document.getElementById("map"),
                mapOptions);
            directionsDisplay.setMap(map);
            directionsDisplay.setPanel(document.getElementById('right-panel'));

            var control = document.getElementById('floating-panel');
            //control.style.display = 'block';
            map.controls[google.maps.ControlPosition.TOP_CENTER].push(control);

            // adding the user current location to teh marker
            addMarker(currentLatLng.latitude, currentLatLng.longitude, "You are here. Please wait. System is locating near by locations");

            // Ajax call to get the nearest locations from DB.
            jQuery.ajax({
                cache: false,
                type: "POST",
                url: "@Url.Action("GetNearByLocations")",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ Currentlat: currentLatLng.latitude, Currentlng: currentLatLng.longitude }),
                success: function (data) {
                    //Adding the marker of nearest locations
                    if (data != undefined) {
                        $.each(data, function (i, item) {
                            // addMarker(item["lat"], item["lng"], item["Name"] + " & Distance: " + (Math.round(0.0 + item["Distance"] / 1000)) + " KM");
                            addMarker(item["lat"], item["lng"], "Click to get directions");

                        })
                    }
                },

                failure: function (errMsg) {
                    alert(errMsg);
                }
            });

            // Add marker function to add the markers and information window settings
            function addMarker(x, y, locationName, distance) {
                var infowindow = new google.maps.InfoWindow({
                    content: locationName
                });

                var location = new google.maps.LatLng(x, y);
                var marker = new google.maps.Marker({
                    position: location,
                    map: map,
                    title: locationName,
                });
                infowindow.open(map, marker);

                // Call the funtion to draw the route map on the clicking on the map marker
                marker.addListener('click', function () {
                    infowindow.open(map, marker);
                    calculateAndDisplayRoute(directionsService, directionsDisplay, x, y);
                });
            }

            //function to draw the route from the current location to the clicked location on the map
            function calculateAndDisplayRoute(directionsService, directionsDisplay, x, y) {

                // Origin is user current location
                var latlngSource = { lat: parseFloat(currentLatLng.latitude), lng: parseFloat(currentLatLng.longitude) };

                //destination is clicked marker on the map
                var latlangDestination = { lat: parseFloat(x), lng: parseFloat(y) };
                directionsService.route({
                    origin: latlngSource, //Source
                    destination: latlangDestination, //destination
                    travelMode: 'DRIVING'
                }, function (response, status) {
                    if (status === 'OK') {
                        directionsDisplay.setDirections(response);
                    } else {
                        window.alert('Directions request failed due to ' + status);
                    }
                });
            }
        }

        //show error formats incase the location is not found.
        function showError(error) {
            if (error.code == 1) {
                $("#message").html("User denied the request for Geolocation.");
            }
            else if (error.code == 2) {
                $("#message").html("Location information is unavailable.");
            }
            else if (error.code == 3) {
                $("#message").html("The request to get user location timed out.");
            }
            else {
                $("#message").html("An unknown error occurred.");
            }
        }
    }

    // Google maper - starting point
    google.maps.event.addDomListener(window, 'load', initialize);
</script>

Component_1: 组件中没有ngAfterViewInit,静物的生命周期是从某个常见的地方触发的。

Component_2: 该组件具有ngAfterViewInit,

ngAfterViewInit() {
    $('[data-toggle="tooltip"]').tooltip();
  }

在这种情况下,ngPlaceViewInit会从两个位置(公共位置以及其各自的组件)触发

有什么办法可以做到这一点?

谢谢

1 个答案:

答案 0 :(得分:0)

没有一个“通用的地方”可以为所有组件定义全局行为。

相反,您可以创建以下类并使所需的组件对其进行扩展:

export abstract class BaseComponent implements AfterViewInit {
  /**
   * View initialization behavior. Note that derived classes must not implement AfterViewInit .
   * Use viewInit() on derived classes instead.
   */
  ngAfterViewInit(): void {
    // Your code
    this.viewInit();
  }

  /**
   * Function that allows derived components to define an additional view initialization behavior
   */
  abstract viewInit(): void;
}