Currently, I'm developing a mobile application with NativeScript using Typescript/JavaScript. The code below is executed after completing a Bluetooth scan in the app. The main task is to identify the correct service from the available options. Unfortunately, when attempting to select the desired service, an issue arises at the line services.filter(function (obj) {
. Despite looking through the error log, I can't seem to make sense of it...
console.log("Connect Variable");
var services: Array<string>;
var service: any;
services = []; //initialize array
bluetooth.connect(
{
UUID: _peripheral.UUID,
onConnected: function (peripheral) {
console.log("------- Peripheral connected: " + JSON.stringify(peripheral));
peripheral.services.forEach(function (value) {
console.log("---- ###### adding service: " + value.UUID);
services.push(value);
});
service = peripheral.services.filter(function (obj) {
return obj.UUID == 'A000';
});
},
}
);
Here's the output from the console log:
CONSOLE LOG file:///app/Pages/Home/home.component.js:145:32: ---- ###### adding service: A000
CONSOLE LOG file:///app/Pages/Home/home.component.js:145:32: ---- ###### adding service: 180A
***** Fatal JavaScript exception - application has been terminated. *****
Native stack trace:
1 0xbea99 NativeScript::FFICallback<NativeScript::ObjCMethodCallback>::ffiClosureCallback(ffi_cif*, void*, void**, void*)
2 0x4ae381 ffi_closure_inner_SYSV
3 0x4b20b8 ffi_closure_SYSV
...
30 0x9e943 NativeScript::GlobalObject::moduleLoaderEvaluate(JSC::JSGlobalObject*, JSC::ExecState*, JSC::JSValue, JSC::JSValue)
31 0x44c4f9 JSC::ModuleLoaderObject::evaluate(JSC::ExecState*, JSC::JSValue, JSC::JSValue)
JavaScript stack trace:
1 onConnected@file:///app/Pages/Home/home.component.js:157:55
2 ...
3 UIApplicationMain@[native code]
4 start@file:///app/tns_modules/application/application.js:233:26
5 @file:///app/tns_modules/nativescript-angular/application.js:65:26
<p>Any ideas on what may be causing this error?</p>
<h1>Update:</h1>
<p>After taking Vladimir's advice, here’s the revised code:</p>
<pre><code>for (let i = 0; i < peripheral.service.count; i++) {
if (peripheral.services.objectAtIndex(i).UUID == 'A000') {
service = peripheral.services.objectAtIndex(i);
console.log("selected service: ");
}
}
However, despite this update, the following error persists:
JavaScript error: file:///app/Pages/Home/home.component.js:98:56: JS ERROR TypeError: undefined is not an object (evaluating 'peripheral.service.count')