简体   繁体   中英

Angular 6- importing variable from JS file

I am building a project with Angular 6 that requires me to import styles from an external js file in order to build a custom Google Map. However, it doesn't seem to be importing into my.ts file correctly. Any help would be great!

In my component

import {MapStyles} from './mapstyle.js'

@Component({
selector: 'map',
template: '<div #tref style="width:100%; height:100%;"></div>'
})

export class Map implements AfterViewInit {
  ...
  ngAfterViewInit() {
    console.log(MapStyles)  //is 'undefined'
  }
  const mapProperties = {
      styles: MapStyles
  };
}

The file I'm trying to import (mapstyle.js):

export var MapStyles = [
  {
  "featureType": "water",
  "elementType": "geometry.fill",
  "stylers": [
    {
      "color": "#d3d3d3"
    }]
  },
 ...

I've tried things such as

import * as MapStyles from './mapstyle.js'

and

var MapStyles = [...]

but no luck. thanks!

This is how you can import and use a variable from an imported file in Angular X projects.

map-config.ts

export const mapStyle = [
    {
        'elementType': 'labels.icon',
        'stylers': [
            {
                'visibility': 'off'
            }
        ]
    },
    {
        'featureType': 'poi.medical',
        'elementType': 'labels.icon',
        'stylers': [
            {
                'visibility': 'off'
            }
        ]
    }
];

map.components.ts

import { Component, OnInit } from '@angular/core';
import { mapStyle } from './map-config';

@Component({
  selector: 'app-map', 
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.scss']
})

export class MapComponent implements OnInit {

  mapStyle = mapStyle;

  constructor() { 
    // 
  }

}

I am considering MapStyles is a variable which is from external js file.

I had a similar requirement and this is how I have solved it,

I had loaded javascript file from root component and I am trying to use the variable inside sub component as shown below.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM