使用JavaScript扩展typescript库

6

我正在使用Ionic 3构建一个简单的地图应用程序,为了呈现地图,我正在使用带有OpenStreet地图瓦片leaflet(打字版本)

我想让用户有可能下载和缓存地图,因此我找到了leaflet-offlinehere,并且想要使用它,因为它允许我使用localstorage来存储图像。

现在我的问题是,我正在尝试将typescript与javascript混合使用,但我无法弄清楚如何使其正常工作。

我已经做了什么以及问题所在:

我安装了leaflet typed版本,然后安装了leaflet-offline javascript版本。

现在我在页面中导入它们,如下所示:

import * as leaflet from 'leaflet';
import 'leaflet-offline';

现在,如果我按照示例所述尝试使用该库,我会收到一个typescript错误,指示对象TileLayer中不存在属性offline。
leaflet.tileLayer.offline('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', tilesDb, {
    attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
    subdomains: 'abc',
    minZoom: 13,
    maxZoom: 19,
    crossOrigin: true
}).addTo(this.map);

为了避免这种情况,我添加了。
export namespace tileLayer {
function wms(baseUrl: string, options?: WMSOptions, offline?: any): TileLayer.WMS;
function offline(url?: any, tilesDb?: any, options?: any): any;
}

offline函数位于tileLayer本身的命名空间中。

当前问题 目前当我尝试运行应用程序时,除了实际的地图之外,一切都正常,我看不到它,并且当我查看它时得到的错误是以下内容:

ERROR TypeError: Cannot read property 'then' of null at NewClass.getTileUrl (vendor.js:163411) at NewClass.createTile (vendor.js:163389) at NewClass._addTile (vendor.js:79419) at NewClass._update (vendor.js:79310) at NewClass._setView (vendor.js:79171) at NewClass._resetView (vendor.js:79129) at NewClass.fire (vendor.js:68787) at NewClass._move (vendor.js:72343) at NewClass._onZoomTransitionEnd (vendor.js:72800) at NewClass._catchTransitionEnd (vendor.js:72732)

我确定我犯了一些愚蠢的错误,但是我在这个问题上浪费了很多时间。

有人知道如何解决这个问题吗?

2个回答

2
你可以在源代码中查看:https://github.com/robertomlsoares/leaflet-offline/blob/master/src/TileLayer.Offline.js,你会发现这里出现了故障:
    var resultPromise = this._tilesDb.getItem(dbStorageKey).then(function (data) {

所以对于

的调用
_tilesDb.getItem(dbStorageKey)

代码返回null,此时代码尝试在null上调用'then'。

由于tilesDB是您自己提供的内容,因此您可以在getItem函数中设置断点以查看发生了什么。在某个时刻,您从getItem函数返回了null。

getItem应该执行的操作:

// return Promise that has the image Blob/File/Stream.

getItem方法所提供的关键字是您提供的URL,该URL经过正则表达式替换后得到(请参见同一源文件中的_getStorageKey函数)。

1

无法读取 null 的属性 'then'

then 从应用于其上的函数接收到 null 时,Typescript 会报出这个错误。因此,请检查您的自定义函数是否缺少返回语句。

现在,不要直接在初始化时将图层添加到地图中。尝试使用以下代码替换您现有的代码:

const offlineLayer = leaflet.tileLayer.offline('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', tilesDb, {
    attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
    subdomains: 'abc',
    minZoom: 13,
    maxZoom: 19,
    crossOrigin: true
});

offlineLayer.addTo(this.map)

检查地图的引用,无论是this.map还是您代码中的其他引用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接