我使用 Yandex Maps API 和 Angular 6。当我启动 Angular CLI 服务器时,我总是在控制台中得到以下信息:
MapsComponent_Host.ngfactory.js?[sm]:1
错误 ReferenceError: ymaps 未在 MapsComponent.push../src/app/main-layout/main-layout/maps.component.ts.MapsComponent.ngOnInit (maps.component.ts:19) 在 checkAndUpdateDirectiveInline (core.js :9243) 在 checkAndUpdateNodeInline (core.js:10507) 在 checkAndUpdateNode (core.js:10469) 在 debugCheckAndUpdateNode (core.js:11102) 在 debugCheckDirectivesFn (core.js:11062) 在 Object.eval [as updateDirectives] (MapsComponent_Host. ngfactory.js? [sm]:1) 在 Object.debugUpdateDirectives [as updateDirectives] (core.js:11054) 在 checkAndUpdateView (core.js:10451) 在 callViewAction (core.js:10692)
但是我走完路由,比如到一个/login组件再回去之后,地图突然出现了。
我的 index.html:
<!doctype html>
<html lang="en">
<head>
...
</head>
<body>
</body>
<script src="https://api-maps.yandex.ru/2.1/?apikey=...&lang=ru_RU"type="text/javascript"></script>
...
</html>
maps.component.html 有:
<div id="map" style="width: 600px; height: 400px"></div>
maps.component.ts 包含:
import {Component, OnInit} from '@angular/core';
import {MainLayoutService} from '../main-layout.service';
declare var ymaps:any;
@Component({
selector: 'app-dashboard',
templateUrl: './maps.component.html'
})
export class MapsComponent implements OnInit {
properties: object;
public map :any;
constructor(private service: MainLayoutService) {
}
ngOnInit() {
ymaps.ready().then(() => {
this.map = new ymaps.Map('map', {
center: [50.450100, 30.523400],
zoom: 6
});
});
}
}
将地图加载脚本移动到,
head以便在使用 DOM 之前完全加载。此外,Uncaught TypeError: Cannot set property 'map' of undefined由于上下文丢失而发生错误,您需要绑定它:或者使用箭头函数: