非常简单的问题
我正在尝试 ang 2 和离子 2。
使用以下代码 -
主文件 -
/// <reference path="../../../node_modules/@angular/platform-browser/src/browser.d.ts" />
import {Component} from '@angular/core';
import {Platform} from 'ionic-angular';
import {NavController} from 'ionic-angular';
import {Network} from 'ionic-native'
@Component({
templateUrl: 'build/pages/items-map/items-map.html'
})
export class ItemsMap {
constructor(private platform : Platform) {
console.log(navigator.Connection);
}
}
每当我使用 gulp build 构建项目时,我都会得到 -
错误 TS2339:类型"导航器"上不存在属性"连接"。
有什么帮助吗?我知道记录了一些类似的问题,但没有一个有任何明确的答案
这是 TypeScript 定义问题。它需要插件的 TypeScript 定义。使用 npm 安装它。
npm install @types/cordova-plugin-network-information --save
如果不起作用,请尝试Network.type
而不是navigator.connection
。
您可以根据 W3C 规范草案为网络信息 API 创建自定义类型定义。
以下代码段使用了 2020 年 5 月 11 日的社群小组报告草案,saveData
属性来自 2022 年 1 月 12 日的社群小组报告草案。
// network-information-api.d.ts
declare interface Navigator extends NavigatorNetworkInformation {}
declare interface WorkerNavigator extends NavigatorNetworkInformation {}
declare interface NavigatorNetworkInformation {
readonly connection?: NetworkInformation
}
type Megabit = number
type Millisecond = number
type EffectiveConnectionType = '2g' | '3g' | '4g' | 'slow-2g'
type ConnectionType =
| 'bluetooth'
| 'cellular'
| 'ethernet'
| 'mixed'
| 'none'
| 'other'
| 'unknown'
| 'wifi'
| 'wimax'
interface NetworkInformation extends EventTarget {
readonly type?: ConnectionType
readonly effectiveType?: EffectiveConnectionType
readonly downlinkMax?: Megabit
readonly downlink?: Megabit
readonly rtt?: Millisecond
readonly saveData?: boolean
onchange?: EventListener
}
TypeScript 中对网络信息 API 的本机支持是在 #44842 中添加的,具有有限的属性。
如果您将其更改为" navigator['connection']
"可能会解决问题,或者像有人建议的那样" navigator.type
"。但是我在您的代码中看到一个 lil 问题,您没有声明" navigator
"!我建议您在@Component decorator
上方执行此操作,添加如下:
declare var navigator;
@Component decorator({
.....
})
然后更改为"navigator.type"或"navigator['连接'],任何适合您的!
希望这有帮助。
看起来您已经在导入网络类,因此您可以通过调用 Network.connection
来获取连接类型。此属性的基础代码将返回navigator.connection.type
。
因为通过这种方式,您可以通过Ionic的TypeScript声明类(network.d.ts)访问它,所以错误将不再发生。
请注意,使用 Network 类时,请务必将 Cordova 插件cordova-plugin-network-information
添加到 config.xml 文件中。
例
import {Component} from '@angular/core';
import {Platform} from 'ionic-angular';
import {NavController} from 'ionic-angular';
import {Network} from 'ionic-native'
@Component({
templateUrl: 'build/pages/items-map/items-map.html'
})
export class ItemsMap {
constructor(private platform : Platform) {
console.log(Network.connection);
}
}