简体   繁体   English

Angular 6-从 JS 文件导入变量

[英]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.我正在使用 Angular 6 构建一个项目,该项目要求我从外部 js 文件导入样式以构建自定义 Google 地图。 However, it doesn't seem to be importing into my.ts file correctly.但是,它似乎没有正确导入到 my.ts 文件中。 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):我要导入的文件 (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.这就是在 Angular X 项目中导入和使用导入文件中的变量的方法。

map-config.ts地图配置.ts

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

map.components.ts地图.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.我正在考虑MapStyles是一个来自外部 js 文件的变量。

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.我已经从根组件加载了 javascript 文件,我正在尝试使用子组件内的变量,如下所示。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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