gpt4 book ai didi

javascript - 在 Ionic/Angular 项目中使用 ngCordova 时未定义 $cordovaBLE

转载 作者:行者123 更新时间:2023-11-28 07:01:57 26 4
gpt4 key购买 nike

我有一个基于 Phonegap 构建的 AngularJS/Ionic 应用程序。我正在尝试将 ngCordova 与 cordova-plugin-ble-central 插件(ngCordova 中的 $cordovaBLE)一起使用。无论我尝试什么,$cordovaBLE 都是未定义的。该调用是在按钮的事件处理程序中调用的服务中进行的。

我的index.html包含的是

<script src="js/thirdparty/ionic.bundle.min.js"></script>
<script src="js/thirdparty/ng-cordova.js"></script>
<script src="cordova.js"></script>

我的应用程序注入(inject)是

angular.module('myapp', [
'ionic',
'ngCordova',
'myapp.controller',
'myapp.service'
]);

我的 Controller 定义是

angular.module('myapp.controller')

.controller('settingsCtrl', ['commServ', function (commServ) {
var controller = this;

// Bluetooth ------------
controller.scan = function () {
commServ.getDevices()
};
}])

我的服务定义是(myapp.service 在其他地方定义)

angular.module('myapp.service')

.factory('commServ', [function ($cordovaBLE) {
// Get bluetooth devices
service.getDevices = function () {
console.log($cordovaBLE);

return { error: null, success: true, value: [{ name: "Steve's Device" }] };
};
}

控制台中的输出始终为“未定义”。

最佳答案

我猜你已经安装了这个插件:

cordova plugin add com.megster.cordova.ble

我注意到您的代码中的一些内容。

当您创建新模块时,就像使用 myapp.servicemyapp.controller 一样,您必须使用以下格式:

angular.module('myapp.service', [])

请注意服务模块名称后面的方括号。

您的 Controller 的模块称为awire.controller,但您将其注入(inject)到主模块中,例如myapp.controller

您的服务还存在另一个问题。当您注册服务时,您始终必须将其返回,如 documents 中所示。 .

您正在返回一个对象

return { error: null, success: true, value: [{ name: "Steve's Device" }] };

但您没有实例化该服务:

The service factory function generates the single object or function that represents the service to the rest of the application. The object or function returned by the service is injected into any component (controller, service, filter or directive) that specifies a dependency on the service.

我使用 john papa 的 style guides 中的模式您的服务将如下所示:

(function() {

'use strict';

angular
.module('myapp.service', [])
.factory('commServ', commServ);

commServ.$inject = ['$cordovaBLE'];

/* @ngInject */
function commServ($cordovaBLE) {

console.log("factory => commServ => CREATE");

var service = {
getDevices: getDevices
};

return (service);

function getDevices() {
console.log($cordovaBLE);
return {
error: null,
success: true,
value: [{
name: "Steve's Device"
}]
};
}
}

})();

我已经在我的 Android 设备上进行了测试,它工作正常。

enter image description here

关于javascript - 在 Ionic/Angular 项目中使用 ngCordova 时未定义 $cordovaBLE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32061018/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com