【问题标题】:Angular 6- importing variable from JS fileAngular 6-从JS文件导入变量
【发布时间】:2019-09-19 08:23:59
【问题描述】:

我正在使用 Angular 6 构建一个项目,该项目需要我从外部 js 文件导入样式以构建自定义 Google 地图。但是,它似乎没有正确导入到我的 .ts 文件中。任何帮助都会很棒!

在我的组件中

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
  };
}

我要导入的文件(mapstyle.js):

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

我已经尝试过诸如

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

var MapStyles = [...]

但没有运气。谢谢!

【问题讨论】:

  • 尝试将其保存为 Typescript 文件而不是 JavaScript 文件
  • @HariniP 谢谢,但我的文件不是 json
  • @HariniP 所以我将它转换为一个 .ts 文件,像 import {MapStyles} from './mapstyle' 一样导入它,然后当我稍后在我的组件中使用我的 mapProperties 时,我不得不把 在它前面,但它起作用了!谢谢

标签: javascript angular google-maps import


【解决方案1】:

这是在 Angular X 项目中导入和使用导入文件中的变量的方法。

ma​​p-config.ts

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

ma​​p.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() { 
    // 
  }

}

【讨论】:

    【解决方案2】:

    我正在考虑 MapStyles 是一个来自外部 js 文件的变量。

    我有类似的要求,这就是我解决它的方法,

    我已经从根组件加载了 javascript 文件,我正在尝试使用子组件内的变量,如下所示。

    【讨论】:

      猜你喜欢
      • 2018-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多