Features #2288 » TB_ctx_Angular_v3_Final.docx
ThingsBoard CE 4.2.1.1 Giải Phẫu Toàn Diện self.ctx Và Angular Template Trong Widget Phần 1: Toàn bộ properties ctx | Phần 2: Angular Template | Phần 3: Subscriptions & Data flow Phần 4: Pipes & Utilities | Phần 5: Patterns nâng cao | Phần 6: Debug & Troubleshooting |
| PHẦN 1: self.ctx – BẢN ĐỒ ĐẦY ĐỦ |
1. self.ctx La Gi?
Self.ctc (kiểu WidgetContext) là object trong tâm của mọi custum widget
trong ThingsBoard. Đây là cầu nối giữa code widget va toàn bộ hệ thống:
dữ liệu IoT thời gian thực, Angular framework, ThingsBoard service,
dashboard state, RPC API đến thiết bị và biển báo.
Hình dung self.ctx ;à “hộp công cụ” mã ThingsBoard cung cập sẵn cho bạn
– mọi thứ bạn cần đều có trong đó, tự đọc dữ liệu cảm biến đến mơ
dialog, tự định hướng dashboard đến gọi RESTAPI.
[TIP] Cách nhanh nhất để khám phá ctx Trong oninit(), viết: console.log(self.ctx); rồi nhán nút Run. Mở DevTools (F12) > Console, expand object ctx để thấy toàn bộ properties thực tế của phiên bản TB bạn đang dung. Mọi phiên bản mới có thể thêm properties mới. |
1.1 Chinh Sơ Đồ Tổng Quan – Nhóm Chính
| [1] Dữ liệu & Config | [2] Angular | [3] Sub-APIs | [4] Utilities |
| data datasources timeWindow settings widgetConfig units / decimals widgetId isEdit / isMobile width / height | $scope $container $containerParent ngZone detectChanges() updateWidgetParams() | defaultSubscription controlApi (RPC) actionsApi subscriptionApi timewindowFunctions stateController broadcastService | http translate date utils pageLink() servicesMap dashboard widgetUtils |
1.2 Bảng Toàn Bộ Properties – Nhóm Dữ Liệu & Cấu Hình
| Property | Kiểu dữ liệu | Mô tả chi tiết |
| ctx.data | Array<DatasourceData> | Mảng dữ liệu chính. Mỗi phần tử ứng với một data key được cấu hình. Cấu trúc: [{datasource, dataKey, data: [[timestamp_ms, value], ...]}]. Đây là nguồn dữ liệu IoT chính. |
| ctx.datasources | Array<Datasource> | Mảng thông tin các datasource đang kết nối. Mỗi phần tử chứa: name, entityId, entityType (DEVICE/ASSET...), entityName, aliasName, dataKeys[]. Dùng để lấy tên/ID thiết bị. |
| ctx.timeWindow | WidgetTimewindow | Thời gian hiện tại của widget. Gồm: minTime (ms UTC), maxTime (ms UTC), interval (ms – độ phân giải khi gom nhóm). Chỉ áp dụng cho Time Series và Alarm widget. |
| ctx.settings | Object | Đối tượng chứa cấu hình từ Settings Schema. Ví dụ: ctx.settings.primaryColor. Các giá trị mặc định từ schema sẽ tự động gán nếu người dùng chưa cấu hình. |
| ctx.widgetConfig | WidgetConfig | Cấu hình chung của widget trong phần Appearance: color, backgroundColor, padding, margin, title, showTitle, dropShadow, titleFont, titleColor, showTitleIcon, titleIcon.... |
| ctx.units | String | Đơn vị hiển thị (ví dụ: "°C", "kWh", "%"). Người dùng đặt trong tab Basic của widget settings. Dùng cho gauge, card đơn giản, hoặc bất kỳ widget nào hiển thị một giá trị. |
| ctx.decimals | Number | Số chữ số thập phân để hiển thị giá trị. Ví dụ: 2 → hiển thị "23.45", 0 → hiển thị "23". Người dùng đặt trong tab Basic. |
| ctx.widgetId | String | UUID duy nhất của widget instance trên dashboard. Rất quan trọng: dùng làm ID cho canvas/element HTML để tránh xung đột khi có nhiều widget cùng loại. |
| ctx.isEdit | Boolean | true khi dashboard đang ở chế độ chỉnh sửa (biểu tượng bút chì). Dùng để disable các nút control, hiển thị placeholder, ngăn người dùng click nhầm khi chỉnh sửa. |
| ctx.isMobile | Boolean | Gán = true để ẩn toàn bộ title bar của widget. Phải gọi ctx.updateWidgetParams() sau khi thay đổi để áp dụng. |
| ctx.hideTitlePanel | Boolean | Gan = true de an toan bo title bar cua widget. Phai goi ctx.updateWidgetParams() sau khi thay doi de ap dung. |
| ctx.widgetTitle | String | Ghi đè tiêu đề widget tại runtime. Phải gọi ctx.updateWidgetParams() sau khi set. Hữu ích khi muốn hiển thị tên thiết bị đang xem lên tiêu đề. |
| ctx.width | Number | Chiều rộng hiện tại của widget container (px). Được cập nhật trước mỗi lần gọi onResize(). |
| ctx.height | Number | Chiều cao hiện tại của widget container (px). Được cập nhật trước mỗi lần gọi onResize(). |
1.3 Nhóm Angular -- Giao Tiếp HTML Template
| Property / Function | Kiểu | Mô tả và cách dùng |
| ctx.$scope | IDynamicWidgetComponent | Scope của Angular component – “cầu nối” giữa JS và HTML template. Có thể gán biến: ctx.$scope.myVar = value. Định nghĩa hàm xử lý sự kiện: ctx.$scope.onClick = function(){}. Trong HTML dùng {{ctx.$scope.myVar}} và (click)="ctx.$scope.onClick()". |
| ctx.$container | jQuery Object | jQuery wrapper cho container div của widget. Dùng để truy cập/sửa DOM: ctx.$container.find(".class").css("color","red"). Nên cache các element con hay dùng trong onInit() để tăng hiệu năng. |
| ctx.$containerParent | jQuery Object | jQuery wrapper cho parent container bên ngoài widget. Ít dùng trong thực tế, nhưng cần khi phải tương tác với layout bên ngoài widget container. |
| ctx.ngZone | NgZone | Angular NgZone service. Goi ctx.ngZone.run(()=>{...}) khi ban co code async tu ngoai Angular (callback cua setTimeout, external library, native WebSocket...) can cap nhat UI. |
| ctx.detectChanges() | Function | Kích hoạt Angular change detection để render lại HTML template. Bắt buộc gọi sau mỗi lần thay đổi biến trong ctx.$scope. Nếu không gọi, UI sẽ không cập nhật dù dữ liệu đã thay đổi. |
| ctx.updateWidgetParams() | Function | Áp dụng các thay đổi runtime-property như widgetTitle và hideTitlePanel lên widget. Phải gọi sau khi thay đổi các property này để chúng có hiệu lực. |
1.4 defaultSubscription -- Subscription Chính
ctx.defaultSubscription là IWidgetSubscription -- object subscription
quan trọng nhất. Nó là "proxy" cho ctx.data va ctx.datasources nhưng có
thêm nhều thông tin chi tiết hơn, dặc biệt cần thiết cho Alarm widget.
| defaultSubscription.property | Dùng khi nào/ ý nghĩa |
| defaultSubscription.data | Tương tự ctx.data – mảng dữ liệu của tất cả keys. Một số tài liệu cũ dùng cách này thay cho ctx.data trực tiếp, cả hai đều hợp lệ. |
| defaultSubscription.datasources | Tương tự ctx.datasources – thông tin các datasource đang kết nối. |
| defaultSubscription.alarmSource | Dành cho Alarm widget. Chứa thông tin datasource (entity) mà alarm được đọc từ đó. |
| defaultSubscription.alarms | Chỉ dành cho Alarm widget. Mảng toàn bộ cảnh báo hiện tại theo filter đã cấu hình. |
| defaultSubscription.subscriptionTimewindow | Time window thực sự của subscription (có thể khác ctx.timeWindow nếu người dùng đã override bằng timewindowFunctions). |
| defaultSubscription.timeWindowConfig | Cấu hình time window gốc của subscription trước khi có override. |
1.5 controlApi -- RPC Control API
ctx.controlApi CHỈ dành cho widget loại "RPC Control". Cùng cấp các
hàm gửi lệnh RPC đến thiết bị IoT.
| Function | Tham so | Mo ta |
| controlApi.sendOneWayCommand(method, params, timeout) | - method: string - params: object - timeout: số ms |
Gửi lệnh RPC một chiều – KHÔNG chờ phản hồi từ thiết bị. Phù hợp cho các thao tác như: bật/tắt relay, gửi cảnh báo, đặt chế độ. Trả về Observable, có thể subscribe để biết khi lệnh đã gửi |
| controlApi.sendTwoWayCommand(method, params, timeout) | - method: string - params: object - timeout: số ms |
Gửi lệnh RPC hai chiều – CÓ phản hồi từ thiết bị. Dùng khi cần xác nhận thiết bị đã thực hiện hoặc cần dữ liệu trả về. Trả về Observable. |
| controlApi.completedCommand() | (khong co tham so) | Dừng và hủy RPC command đang chạy. Nên gọi trong onDestroy() hoặc khi người dùng hủy thao tác để tránh memory leak. |
// Ví dụ đầy đủ: Bật đèn LED và chờ xác nhận từ thiết bị self.ctx.$scope.turnOnLED = function() { if (self.ctx.$scope.loading) return; // Tránh double-click self.ctx.$scope.loading = true; self.ctx.$scope.statusMsg = "Đang gửi lệnh..."; self.ctx.detectChanges(); self.ctx.controlApi.sendTwoWayCommand( "setLED", // Tên method RPC trên firmware { pin: 13, state: true }, // Tham số truyền xuống thiết bị 5000 // Timeout 5 giây ).subscribe( function(response) { // response là dữ liệu trả về từ thiết bị (nếu có) self.ctx.$scope.isOn = true; self.ctx.$scope.statusMsg = "Đèn đã bật thành công"; self.ctx.$scope.loading = false; self.ctx.detectChanges(); }, function(error) { self.ctx.$scope.statusMsg = "Lỗi: " + (error.message || "Hết timeout"); self.ctx.$scope.loading = false; self.ctx.detectChanges(); } ); }; |
1.6 actionsApi – Tích hợp Dashboard Actions
ctx.actionsApi cho phép widget kích hoạt các actions mà người dùng
đã cấu hình trong tab "Actions" của phần widget settings. Đây là
cơ chế kết nối widget với các hành động như: mở một dashboard state,
điều hướng đến URL, mở dialog, gọi hàm tùy
| Function | Tham số | Mo ta ngan gon |
| actionsApi.getActionDescriptors(actionSourceId) | - $event: sự kiện DOM - descriptor: lấy từ getActionDescriptors - entityId, entityName: thông tin entity - additionalParams: tham số bổ sung |
Lấy danh sách action descriptors cho một action source ID. Ví dụ: actionsApi.getActionDescriptors("rowClick") để lấy các actions của sự kiện click vào một dòng. |
| actionsApi.handleWidgetAction($event, descriptor, entityId, entityName, additionalParams) | Kích hoạt một action cụ thể. Truyền $event từ DOM, descriptor từ getActionDescriptors, cùng thông tin entity để các actions như “Navigate to dashboard state” biết phải dùng entity nào. | |
| actionsApi.getActiveEntityInfo() | Lấy thông tin entity đầu tiên trong widget (entityId, entityName, entityType). Hữu ích khi cần biết widget đang hiển thị dữ liệu của thiết bị nào. | |
| actionsApi.openDashboardStateInSeparateDialog(stateId, params, title, hideToolbar, width, height) | - stateId: ID của dashboard state - params: tham số truyền vào - title: tiêu đề dialog - hideToolbar: ẩn/hiện toolbar - width, height: kích thước dialog |
Mở một dashboard state trong hộp thoại riêng. Rất phổ biến trong table widget khi click vào một dòng để xem chi tiết. |
| actionsApi.openDashboardStateInPopover($event, stateId, params, placement, hideOnOutsideClick, ...) | - $event: sự kiện DOM - stateId: ID của dashboard state - params: tham số truyền vào - placement: vị trí hiển thị - hideOnOutsideClick: tự đóng khi click ra ngoài |
Mở dashboard state trong popover (nổi lên trên element). Tương tự tooltip nhưng là cả một dashboard. |
// Ví dụ: Table widget -- click vào row để mở dialog chi tiết self.onInit = function() { self.ctx.$scope.onRowClick = function($event, row) { // Lấy action descriptors của nguồn "rowClick" var descriptors = self.ctx.actionsApi.getActionDescriptors("rowClick"); if (descriptors.length > 0) { // Kích hoạt action đầu tiên được cấu hình self.ctx.actionsApi.handleWidgetAction( $event, descriptors[0], { entityType: row.entityType, id: row.entityId }, row.name ); } }; // Hoặc mở trực tiếp bằng code (không cần action trong settings) self.ctx.$scope.openDeviceDetail = function(deviceId, deviceName) { self.ctx.actionsApi.openDashboardStateInSeparateDialog( "device_detail", // ID của state cần mở { entityId: { entityType: "DEVICE", id: deviceId }, entityName: deviceName }, "Chi tiết: " + deviceName, false, // hiển thị dashboard toolbar 900, // chiều rộng dialog (px) 650 // chiều cao dialog (px) ); }; }; |
1.7 stateController – Điều khiển Dashboard State
ctx.dashboard.stateController là công cụ quản lý navigation giữa các
state của dashboard. Dùng để chuyển trang, truyền tham số giữa các
state, và đọc thông tin entity đang được hiển.
| Function | Mo ta va vi du su dung | |
| stateController.openState(id, params, openRightLayout) | - id: ID của state cần mở - params: object chứa entityId, entityName để state mới biết cần hiển thị gì - openRightLayout: mở ở layout bên phải (nếu có) |
Chuyen sang state khac. Params la object chua entityId, entityName de state moi biet can hien thi gi. VD: openState("detail", {entityId:{entityType:"DEVICE",id:"..."}, entityName:"Cam bien 1"}) |
| stateController.updateState(id, params) | - id: ID của state hiện tại - params: object tham số mới |
Cap nhat params cua state hien tai ma khong chuyen state. Dung de "refresh" state hien tai voi entity moi. |
| stateController.getStateParams() | Lay toan bo params cua state hien tai. Rat hay dung o state "chi tiet" de biet can hien thi thong tin entity nao. | |
| stateController.getEntityId(entityParamName) | - entityParamName: tên param | Lay entityId theo ten param. VD: getEntityId("entityId") tra ve {entityType:"DEVICE",id:"abc-123..."} |
| stateController.getStateId() | Lay ID cua state dang hien thi. | |
| stateController.getCurrentStateName() | Lay ten hien thi (label) cua state dang hien thi. | |
| stateController.resetState() | Quay ve state mac dinh (state dau tien). | |
| stateController.preserveState() | Luu state params vao preservedState -- dung cho navigation nhieu cap (A -> B -> C -> back). |
// Ví dụ: State "chi tiết thiết bị" -- đọc entity từ params self.onInit = function() { var sc = self.ctx.dashboard.stateController; // Lấy thông tin thiết bị được truyền từ state trước var entityId = sc.getEntityId("entityId"); // entityId = { entityType: "DEVICE", id: "943b8cd0-576a-11e7-..." } var params = sc.getStateParams(); // params = { entityId: {...}, entityName: "Cảm biến nhiệt độ 1" } self.ctx.$scope.deviceName = params.entityName || "Không xác định"; self.ctx.$scope.deviceId = entityId ? entityId.id : null; self.ctx.detectChanges(); // Nút quay lại state trước self.ctx.$scope.goBack = function() { sc.resetState(); }; }; |
1.8 broadcastService – Giao Tiếp Giữa Các Widget
BroadcastService Là kênh pub/sub nội bộ để các widget trao đổi dữ
liệu trực tiếp mà không cần qua server. Ví dụ: Widget A gửi dữ liệu,
Widget B nhận và xử lý – tất cả diễn ra trong cùng một dashboard.
[QUAN TRỌNG] Cách inject BroadcastService đúng trong ThingsBoard v4.x: Phải lấy qua Angular injector như sau: self.broadcastSvc = self.ctx.$scope.$injector.get( self.ctx.servicesMap.get("broadcastService") ); 🔧 Lưu ý: Một số ví dụ cũ dùng cách inject trực tiếp sẽ không còn hoạt động từ phiên bản v3.4+ trở đi. |
// ==== WIDGET GỬI (Publisher) ==== self.onInit = function() { self.bcast = self.ctx.$scope.$injector.get( self.ctx.servicesMap.get("broadcastService") ); // Gắn hàm vào scope để HTML có thể gọi self.ctx.$scope.selectDevice = function(deviceId, deviceName) { self.bcast.broadcast("TB_DEVICE_SELECTED", { id: deviceId, name: deviceName, ts: Date.now() }); // Bất kỳ widget nào đang "on" sự kiện này sẽ nhận được dữ liệu }; }; // ==== WIDGET NHẬN (Subscriber) ==== self.onInit = function() { self.bcast = self.ctx.$scope.$injector.get( self.ctx.servicesMap.get("broadcastService") ); self.bcast.on("TB_DEVICE_SELECTED", function(event, args) { var device = args[0]; // Dữ liệu từ widget gửi self.ctx.$scope.currentDevice = device.name; self.ctx.$scope.deviceId = device.id; self.ctx.detectChanges(); }); }; // ==== QUAN TRỌNG: Hủy đăng ký trong onDestroy ==== self.onDestroy = function() { if (self.bcast) { self.bcast.off("TB_DEVICE_SELECTED"); // Tránh memory leak } }; |
1.9 timewindowFunctions – Điều khiển Time Window
ctx.timewindowFunctions cho phép widget lập trình viên thay đổi khoảng
thời gian xem dữ liệu ngay tại runtime. Rất hữu ích khi xây dựng
widget có tính năng zoom hoặc lọc theo thời gian.
| Function | Tham số mô tả |
| timewindowFunctions.onUpdateTimewindow(startTimeMs, endTimeMs) -
startTimeMs: Unix timestamp (ms) - endTimeMs: Unix timestamp (ms) |
Đổi time window thành một khoảng lịch sử cụ thể. startTimeMs và endTimeMs là thời gian tính bằng milliseconds. Widget sẽ reload dữ liệu theo khoảng thời gian mới. |
| timewindowFunctions.onResetTimewindow() | Reset time window về mặc định: khoảng thời gian được cấu hình ban đầu trong widget settings hoặc dashboard timewindow. |
// Ví dụ: Các nút chọn nhanh khoảng thời gian (Quick time range buttons) self.onInit = function() { self.ctx.$scope.setRange = function(hours) { var now = Date.now(); var start = now - hours * 60 * 60 * 1000; self.ctx.timewindowFunctions.onUpdateTimewindow(start, now); }; self.ctx.$scope.resetRange = function() { self.ctx.timewindowFunctions.onResetTimewindow(); }; }; // HTML: // <button (click)="ctx.$scope.setRange(1)">1 Giờ</button> // <button (click)="ctx.$scope.setRange(24)">24 Giờ</button> // <button (click)="ctx.$scope.resetRange()">Mặc định</button> |
1.10 Utility Services – Các tiện ích thường dùng
| ctx.property | Kiểu | Mô tả và ví dụ thực tế |
| ctx.http | HttpClient | Gọi REST API. Tự động gắn Bearer token nếu gọi cùng host ThingsBoard. Ví dụ: ctx.http.get("/api/tenant/devices").subscribe(...). |
| ctx.translate | TranslateService | Dịch đa ngôn ngữ theo locale hiện tại của ThingsBoard. Ví dụ: ctx.translate.instant("widget.no-data-found") trả về chuỗi đã dịch. |
| ctx.date | DatePipe | Format timestamp thành chuỗi. Ví dụ: ctx.date.transform(1698000000000, "dd/MM/yyyy HH:mm:ss") → "22/10/2023 17:20:00". |
| ctx.utils | UtilsService | Các tiện ích xử lý dữ liệu. Ví dụ: ctx.utils.formatValue(value, decimals, units, insertSpace) để format số đẹp, có locale. formatValue(1234.5, 1, "°C", true) → "1 234.5 °C". |
| ctx.pageLink(size,page,search,sort) | PageLink | Tao doi tuong pagination de goi list API. VD: ctx.pageLink(10, 0, "", {property:"name",direction:"ASC"}). |
| ctx.servicesMap | Map<string,any> | Map các Angular services có sẵn. Dùng để inject: ctx.$scope.$injector.get(ctx.servicesMap.get("deviceService")). |
| ctx.dashboard | Dashboard API | Container chứa stateController và các API cấp dashboard khác. |
| ctx.widgetUtils | WidgetUtils | Các tiện ích bổ sung cho widget: xử lý màu sắc, formatValue nâng cao, xử lý timewindow... |
// Ví dụ đầy đủ sử dụng các utility services self.onInit = function() { // 1. formatValue -- format số đẹp có đơn vị var kw = self.ctx.utils.formatValue(1234.567, 2, "kWh", true); // "1 234.57 kWh" var deg = self.ctx.utils.formatValue(25.3, 1, "°C", true); // "25.3 °C" // 2. DatePipe -- format thời gian var now = self.ctx.date.transform(Date.now(), "dd/MM/yyyy HH:mm:ss"); var time = self.ctx.date.transform(Date.now(), "HH:mm"); // 3. Dịch thông báo theo ngôn ngữ hiện tại var noData = self.ctx.translate.instant("widget.no-data-found"); // 4. Inject DeviceService để lấy danh sách thiết bị var deviceSvc = self.ctx.$scope.$injector.get( self.ctx.servicesMap.get("deviceService") ); var plink = self.ctx.pageLink(20, 0, "", { property: "name", direction: "ASC" }); deviceSvc.getTenantDeviceInfos(plink).subscribe(function(result) { // result.data = mảng các DeviceInfo // result.totalElements, result.totalPages, result.hasNext self.ctx.$scope.deviceList = result.data; self.ctx.detectChanges(); }); }; |
| PHẦN 2: ANGULAR TEMPLATE – CÚ PHÁP ĐẶC BIỆT TRONG HTML |
2. Tại Sao HTML Của Thingsboard Widget “Khác Lạ”?
HTML trong tab HTML của Widget Editor không phải HTML thuần túy. Đó
là Angular Template – một phiên bản mở rộng của HTML với cú pháp đặc
biệt do Angular framework cung cấp. ThingsBoard UI được xây dựng hoàn
toàn bằng Angular 15+, nên mỗi widget cũng chạy trong môi trường Angular
đó.
Điều này có nghĩa là bạn có thể dùng toàn bộ sức mạnh của Angular trong
widget:
-
Data binding hai chiều
-
Structural directives (*ngFor, *ngIf)
-
Built-in pipes
-
Event handling
-
Và cả các Angular Material component (mat-icon, mat-slider...)
[QUY TẮC VÀNG] Luồng dữ liệu JS ↔︎ HTML
|
2.1 Bảng Toàn Bộ Cú Pháp Angular Template
| Cu phap / Directive | Vi du | Giai thich |
| {{ }} -- Interpolation | {{ctx.$scope.temperature}} {{value | number:"1.2-2"}} | Hiển thị giá trị biến JS ra HTML. Khi biến thay đổi và detectChanges() được gọi, UI tự động cập nhật. Có thể kết hợp với pipe bằng dấu `" | "`. |
| [prop] -- Property Binding | [style.color]="ctx.$scope.color" [class.active]="ctx.$scope.isOn" [disabled]="ctx.$scope.loading" [attr.data-id]="ctx.$scope.id" | Bind property/attribute của HTML element với biểu thức JS. Dấu [] báo hiệu đây là expression, không phải string. Cập nhật realtime khi biến thay đổi. |
| (event) -- Event Binding | (click)="ctx.$scope.onClick()" (change)="ctx.$scope.onChange($event)" (mouseenter)="ctx.$scope.onHover($event)" | Lắng nghe DOM event. $event là native DOM Event object (chứa target, clientX, clientY...). Hàm phải được gán vào ctx.$scope trước khi HTML render. |
| [(ngModel)] -- Two-way | [(ngModel)]="ctx.$scope.inputValue" <input [(ngModel)]="ctx.$scope.val"> | Vừa hiển thị giá trị vừa tự động cập nhật khi user nhập. Rất hữu ích cho form, input, slider. FormsModule đã có sẵn trong ThingsBoard. |
| *ngIf | <div *ngIf="ctx.$scope.show"> <div *ngIf="ok; else errTpl"> <ng-template #errTpl>Loi</ng-template> | Hiển thị/ẩn element theo điều kiện. Khi false, element bị xóa khỏi DOM (khác [hidden] chỉ ẩn bằng CSS). Có cú pháp "else" kết hợp với ng-template. |
| *ngFor | <div *ngFor="let item of ctx.$scope.items; let i = index; trackBy: ctx.$scope.trackFn"> | Render loop cho mảng. i là index (0-based). trackBy chỉ định hàm nhận dạng item để Angular chỉ re-render những item thay đổi → tăng hiệu năng cho list lớn. |
| *ngSwitch | <div [ngSwitch]="ctx.$scope.state"> <span *ngSwitchCase="'ok'">Binh thuong</span> <span *ngSwitchCase="'warn'">Canh bao</span> <span *ngSwitchDefault>Khong xac dinh</span> | Switch/case trong template. Gọn hơn chuỗi *ngIf dài. Đặt [ngSwitch] trên container, *ngSwitchCase trên từng nhánh, *ngSwitchDefault cho trường hợp còn lại. |
| [ngClass] | [ngClass]="{ 'status-ok': val < 30, 'status-warn': val >= 30 && val < 40, 'status-danger': val >= 40 }" | Thêm/bỏ nhiều CSS class một lúc theo điều kiện. Object: key là tên class, value là điều kiện boolean. Mạnh hơn [class.name] khi có nhiều class cần điều khiển. |
| [ngStyle] | [ngStyle]="{ 'color': ctx.$scope.fgColor, 'background': ctx.$scope.bgColor, 'font-size': ctx.$scope.fSize+'px' }" | Thêm nhiều inline CSS style theo điều kiện. Object: key là CSS property, value là giá trị. Mạnh hơn [style.prop] khi cần set nhiều style một lúc. |
| Pipe | | {{1234.5 | number:"1.2-2"}} {{ts | date:"dd/MM/yyyy HH:mm"}} {{0.75 | percent:"1.0-0"}} {{text | uppercase}} {{arr | slice:0:5}} | Transform dữ liệu trước khi hiển thị. Các pipe có sẵn: number (định dạng số), date (định dạng ngày giờ), percent, currency, uppercase, lowercase, slice (cắt mảng/chuỗi), json, async. |
| ng-template & ng-container | <ng-template #loadTpl> <mat-spinner></mat-spinner> </ng-template> <div *ngIf="!loading; else loadTpl"> <ng-container *ngFor="let x of items"> | ng-template: định nghĩa block HTML có thể tái sử dụng (dùng với *ngIf else, ngTemplateOutlet). ng-container: wrapper vô hình – cần khi dùng *ngFor nhưng không muốn tạo thêm thẻ DIV. |
2.2 Component Tags Đặc Biệt -- <tb-xxx> va <mat-xxx>
Trong HTML widget, bạn có thể thấy các thẻ lạ như
<tb-time-series-chart-widget [ctx]="ctx">. Đây là Angular Component
– các "mini-app" đưuọc ThingsBoard viết sẵn và đăng ký trong Angular
module.
[GIẢI THÍCH CỐT LÕI] Vì sao viết [ctx]="ctx" chứ không phải ctx="ctx"? Trong Angular, cú pháp [property]="expression" (có dấu []) nghĩa là truyền giá trị (object, số, boolean, …) của biểu thức JS vào property. Nếu không có [], Angular sẽ hiểu là truyền chuỗi literal.
|
<!-- ĐÚNG: Truyền object ctx vào component --> <tb-time-series-chart-widget [ctx]="ctx"></tb-time-series-chart-widget> <!-- SAI: Chỉ truyền chuỗi "ctx" → lỗi runtime --> <tb-time-series-chart-widget ctx="ctx"></tb-time-series-chart-widget> <!-- So sánh với JavaScript: --> <!-- [ctx]="ctx" tương đương với: myFn(ctx) -- truyền biến --> <!-- ctx="ctx" tương đương với: myFn("ctx") -- truyền chuỗi --> |
| Component Tag | Input Binding chính | Dùng để làm gì |
| <tb-time-series-chart-widget> | [ctx]="ctx" | Nhúng sẵn chart time series (ECharts bọc lặp) của ThingsBoard vào widget của bạn. Thường gặp trong bundled/extension widgets. |
| <tb-dashboard-state> | stateId="...", [ctx]="ctx" | Nhúng một dashboard state khác vào trong widget. Tạo nested dashboard bao gồm bên trong một widget. |
| <mat-spinner> | [diameter]="40", [strokeWidth]="3" | Loading spinner của Angular Material. Dùng khi đang load dữ liệu hoặc chờ RPC response. |
| <mat-icon> | [style.color]="...", [class]="..." | Icon Material Design. Cách dùng: thermostat. Tìm icon tại fonts.google.com/icons. |
| <mat-slider> | [min] [max] [step] [(ngModel)]="v" | Thanh trượt input, hay dùng cho RPC control widget (chỉnh độ sáng, nhiệt độ...). |
| <mat-select> + <mat-option> | [(ngModel)]="selected", (selectionChange)="..." | Dropdown select đẹp. Ví dụ: mat-option [value]="x">Nhãn bên trong. |
| <mat-button-toggle-group> | [(ngModel)]="active", (change)="..." | Nhóm nút toggle radio (chọn 1 trong nhiều lựa chọn). Hay dùng cho chọn chế độ/khoảng thời gian. |
| <mat-slide-toggle> | [(ngModel)]="isOn", (change)="..." | Switch bật/tắt đẹp của Material. Hay dùng trong RPC control widget thay cho checkbox. |
2.3 Ví Dụ Thực Tế: Widget Tổng Hợp Nhiều Angular Features
Ví dụ bên dưới dử dụng: *ngFor, *ngIf, [ngClass], (click),
interpolation, pipes, mat-icon va ctx.$scope đẻ xây dựng bảng hiển thị
nhiều cảm biến với nhau theo ngưỡng.
<!-- HTML Template: Bang hien thi nhieu cam bien voi mau nguong --> <div class="sensor-dashboard"> <div class="db-header"> <mat-icon>sensors</mat-icon> <span>{{ ctx.$scope.title }}</span> <span class="spacer"></span> <small>Cap nhat: {{ctx.$scope.lastUpdate | date:"HH:mm:ss"}}</small> </div> <!-- Loading state --> <div *ngIf="ctx.$scope.loading" class="center-box"> <mat-spinner [diameter]="36"></mat-spinner> </div> <!-- Khong co du lieu --> <div *ngIf="!ctx.$scope.loading && ctx.$scope.sensors.length === 0" class="empty-state"> <mat-icon>info_outline</mat-icon> <span>Chua co du lieu</span> </div> <!-- Danh sach cam bien --> <div class="sensor-list" *ngIf="!ctx.$scope.loading && ctx.$scope.sensors.length > 0"> <div *ngFor="let sensor of ctx.$scope.sensors; let i = index" class="sensor-row" [ngClass]="{ 'ok': sensor.status === 'ok', 'warn': sensor.status === 'warn', 'alert': sensor.status === 'alert' }" (click)="ctx.$scope.onSensorClick(sensor, $event)"> <span class="idx">{{ i + 1 }}</span> <mat-icon class="status-icon"> {{sensor.status === "ok" ? "check_circle" : "warning"}} </mat-icon> <span class="name">{{ sensor.name }}</span> <span class="value"> {{ sensor.value !== null ? (sensor.value | number:"1.1-1") : "--" }} <small>{{ ctx.$scope.unit }}</small> </span> </div> </div> </div> |
// JavaScript tuong ung self.onInit = function() { var s = self.ctx.settings; self.ctx.$scope.title = s.title || "Bang Cam Bien"; self.ctx.$scope.unit = s.unit || "°C"; self.ctx.$scope.sensors = []; self.ctx.$scope.loading = true; self.ctx.$scope.lastUpdate = null; self.ctx.$scope.warnVal = s.warnThreshold || 30; self.ctx.$scope.alertVal = s.alertThreshold || 40; self.ctx.$scope.onSensorClick = function(sensor, $event) { console.log("Click:", sensor.name, sensor.value); // Co the goi actionsApi de mo detail }; }; self.onDataUpdated = function() { var warnVal = self.ctx.$scope.warnVal; var alertVal = self.ctx.$scope.alertVal; self.ctx.$scope.sensors = self.ctx.data.map(function(kd) { var raw = (kd.data && kd.data[0]) ? kd.data[0][1] : null; var val = raw !== null ? parseFloat(raw) : null; var status = "ok"; if (val !== null && val >= alertVal) status = "alert"; else if (val !== null && val >= warnVal) status = "warn"; return { name: kd.dataKey.label || kd.dataKey.name, value: val, status: status }; }); self.ctx.$scope.loading = false; self.ctx.$scope.lastUpdate = new Date(); self.ctx.detectChanges(); // BAT BUOC }; |
| PHẦN 3: SUBSCRIPTIONS & CẤU TRÚC DỮ LIỆU CHI TIẾT |
3. Hiểu Sâu Về ctx.data Và Subscription
Phần này giải thích chi tiết cấu trúc của dữ liệu nhận được trong
ctx.data và ctx.datasource == nền tảng để viết bất kỳ widget nào hiển
thị dữ liệu IoT.
3.1 Trúc Chính Xác Của Ctx.Data
// ctx.data là mảng Array<DatasourceData> // Mỗi phần tử tương ứng với một data key (attribute/timeseries) được cấu hình ctx.data = [ { datasource: { type: "entity", // "entity" hoặc "function" name: "Cảm biến phòng A", // Tên datasource / tên entity aliasName: "device_alias", // Tên alias được dùng entityName: "Cảm biến phòng A", entityType: "DEVICE", // DEVICE, ASSET, TENANT... entityId: "943b8cd0-...", // UUID của entity dataKeys: [...] // Mảng các key của datasource này }, dataKey: { name: "temperature", // Tên key thực trên ThingsBoard type: "timeseries", // "timeseries", "attribute", "function" label: "Nhiệt độ", // Nhãn hiển thị (user đặt) color: "#1565C0", // Màu data key (user đặt) settings: {}, // Data key settings từ schema funcBody: "", // Chỉ khi type = "function" }, data: [ // MẢNG DỮ LIỆU THỰC SỰ [1698000000000, "25.3"], // [timestamp_ms, giá_trị] [1698000060000, "25.7"], // giá_trị là STRING, phải parseFloat() [1698000120000, "26.1"], // ... thêm điểm dữ liệu khác ] }, // ... mỗi key được cấu hình là một phần tử trong mảng ]; |
[LƯU Ý QUAN TRỌNG] Giá trị trong data là STRING, không phải Number data[0][1] luôn là chuỗi (ví dụ: "25.3"), ngay cả khi dữ liệu gốc là số. Trước khi tính toán, phải dùng parseFloat() hoặc Number() để chuyển đổi. Nguyên nhân: ThingsBoard serialize dữ liệu thành JSON string trước khi truyền vào widget. ✨ Như vậy, khi làm việc với ctx.data, bạn cần luôn nhớ bước ép kiểu này để tránh lỗi logic trong các phép tính. |
3.2 Các Pattern Đọc Dữ Liệu Theo Loại Widget
Latest Values -- Đọc giá trị mới nhất của nhiều dữ liệu key
// Latest Values widget: mỗi key có duy nhất 1 điểm dữ liệu (mới nhất) self.onDataUpdated = function() { if (!self.ctx.data || self.ctx.data.length === 0) return; self.ctx.data.forEach(function(keyData) { var keyName = keyData.dataKey.name; // "temperature" var keyLabel = keyData.dataKey.label; // "Nhiệt độ" var ts = null; var value = null; if (keyData.data && keyData.data.length > 0) { ts = keyData.data[0][0]; // Timestamp ms value = parseFloat(keyData.data[0][1]); // Giá trị số } // Gán vào scope theo tên key để dùng trong HTML self.ctx.$scope[keyName + "_val"] = value; self.ctx.$scope[keyName + "_ts"] = ts; }); self.ctx.detectChanges(); }; // HTML: {{ctx.$scope.temperature_val | number:"1.1-1"}} °C |
Time Series -- Đọc chuẩn dữ liệu cho biểu đồ đo
// Time Series widget: mỗi key có nhiều điểm dữ liệu trong time window self.onDataUpdated = function() { if (!self.ctx.data || self.ctx.data.length === 0) return; // Xử lý từng key (thường là từng đường trên biểu đồ) var datasets = self.ctx.data.map(function(keyData) { var points = keyData.data || []; return { label: keyData.dataKey.label, color: keyData.dataKey.color, // Mảng [timestamp, số] -- đã chuyển từ string sang float points: points.map(function(p) { return { x: p[0], y: parseFloat(p[1]) }; }) }; }); // Cập nhật Chart.js if (self.chart) { self.chart.data.datasets = datasets.map(function(ds) { return { label: ds.label, borderColor: ds.color, data: ds.points }; }); self.chart.update("none"); } }; |
Alarm Widget – Đọc mảng cảnh báo
// Alarm widget: đọc từ defaultSubscription.alarms self.onDataUpdated = function() { var alarms = self.ctx.defaultSubscription.alarms || []; self.ctx.$scope.alarmList = alarms.map(function(alarm) { return { id: alarm.id.id, type: alarm.type, severity: alarm.severity, // CRITICAL, MAJOR, MINOR, WARNING status: alarm.status, // ACTIVE_UNACK, ACTIVE_ACK, CLEARED_ACK... originName: alarm.originatorName, createdTime: alarm.createdTime, // Unix ms acknowledged: alarm.status.indexOf("ACK") !== -1, cleared: alarm.status.indexOf("CLEARED") !== -1, }; }); self.ctx.$scope.alarmCount = alarms.length; self.ctx.detectChanges(); }; |
3.3 subscriptionApi -- Tạo Subscription Tùy Chỉnh
ctx.subscriptionApi
-
Chức năng: Cho phép tạo các subscription tùy chỉnh – không bị
ràng buộc với datasource đã được cấu hình sẵn trong widget settings. -
Khi nào dùng:
-
Khi cần lấy dữ liệu của entity khác theo yêu cầu riêng.
-
Khi muốn subscribe dữ liệu động, không cố định theo cấu hình ban
đầu của widget. -
Ví dụ: bạn có thể tạo subscription để lấy timeseries từ một thiết bị
khác ngoài datasource mặc định, hoặc subscribe alarm/event theo điều
kiện đặc biệt.
Function |
Mo ta va tham so |
subscriptionApi.createSubscription(options, subscribe) |
Tạo subscription mới.
|
subscriptionApi.createSubscriptionFromInfo(type, subscriptionsInfo, options, useDefaultComponents, subscribe) |
Tạo subscription từ thông tin mô tả (array entity/key).
|
subscriptionApi.removeSubscription(id) |
Xóa subscription theo ID.
|
| PHAN 4: PIPES & UTILITIES -- CAC CONG CU HO TRO |
4. Pipes, Utilities Và Các Service Hay Dùng
4.1 Angular Built-in Pipes -- Biến Đổi Dữ Liệu Trong Template
| Pipe | Cu phap | Ket qua vi du |
| number | {{1234.567 | number:"1.2-2"}} | "1,234.57" – tối thiểu 1 chữ số nguyên, 2 chữ số thập phân. |
| date | {{ts | date:"dd/MM/yyyy HH:mm:ss"}} | "22/10/2023 17:20:00" – theo locale hiện tại. |
| date | {{ts | date:"shortTime"}} | "5:20 PM" – format giờ ngắn gọn. |
| percent | {{0.753 | percent:"1.1-1"}} | "75.3%" – nhân 100 và thêm ký hiệu %. |
| currency | {{1234 | currency:"VND":"symbol":"1.0-0"}} | "1.234 ₫" – định dạng tiền tệ. |
| uppercase | {{ "hello" | uppercase }} | "HELLO" – chuyển thành chữ hoa. |
| lowercase | {{ "HELLO" | lowercase }} | "hello" – chuyển thành chữ thường. |
| slice | {{items | slice:0:3}} | Lấy phần tử từ 0 đến 2 của mảng hoặc chuỗi. |
| json | {{obj | json}} | Chuyển đổi object thành JSON string – rất hữu ích khi debug. |
| async | {{obs$ | async}} | Tự động subscribe Observable, hủy subscribe khi component destroy. |
| keyvalue | {{obj | keyvalue}} | Biến đổi object thành mảng [{key, value}] để dùng trong *ngFor. |
<!-- Ví dụ kết hợp nhiều pipe và điều kiện --> <span [style.color]="ctx.$scope.color"> {{ ctx.$scope.value !== null ? (ctx.$scope.value | number:"1.1-1") : "N/A" }} {{ ctx.$scope.unit | uppercase }} </span> <div *ngFor="let entry of ctx.$scope.obj | keyvalue"> <b>{{entry.key}}</b>: {{entry.value}} </div> |
4.2 ctx.utils.formatValue -- Format Số Chuẩn ThingsBoard
Hàm này rất hay dùng vì nó xử lý dùng với cấu hình locale của
ThingsBoard, bao gồm cả đấu phần cách ngăn, dấu thập phân và khoảng
trắng trước đơn vị.
// Chu ky: ctx.utils.formatValue(value, decimals, units, insertSpace) /* Tham số:
*/ ctx.utils.formatValue(1234.567, 2, "kWh", true); // "1 234.57 kWh" ctx.utils.formatValue(25.3, 1, "°C", true); // "25.3 °C" ctx.utils.formatValue(0.753, 0, "%", false); // "75%" (nhân 100) ctx.utils.formatValue(1000000, 0, "VND", true); // "1 000 000 VND" // Kết hợp với dữ liệu từ ctx.settings: self.onDataUpdated = function() { var raw = self.ctx.data[0].data[0][1]; var val = parseFloat(raw); self.ctx.$scope.displayValue = self.ctx.utils.formatValue( val, self.ctx.decimals, // Lấy từ cấu hình Basic tab của widget self.ctx.units, // Lấy từ cấu hình Basic tab của widget true ); self.ctx.detectChanges(); }; |
4.3 ctx.http -- Gọi API Với Auth Token Tụ Động
ctx.http:
-
Bản chất: Đây chính là Angular HttpClient nhưng đã được
ThingsBoard bổ sung sẵn JWT Bearer token khi gọi đến cùng host. -
Ý nghĩa: Bạn không cần tự thêm header Authorization nữa, mọi
request gửi đi đều đã kèm token hợp lệ. -
Ứng dụng:
-
Rất hữu ích khi muốn truy vấn ThingsBoard REST API trực tiếp từ
bên trong widget. -
Có thể gọi các endpoint như
/api/plugins/telemetry/DEVICE/{deviceId}/values/timeseries,
/api/alarm/{alarmId}, hoặc bất kỳ REST API nào của ThingsBoard. -
Đảm bảo request được xác thực theo user/session hiện tại.
// ==== GET request ==== self.ctx.http.get("/api/tenant/devices?pageSize=20&page=0").subscribe( function(result) { // result.data: Array<DeviceInfo> // result.totalElements: tong so ban ghi // result.hasNext: con trang tiep khong self.ctx.$scope.devices = result.data; self.ctx.detectChanges(); }, function(err) { console.error(err); } ); // ==== POST request (vi du tat alarm) ==== function acknowledgeAlarm(alarmId) { self.ctx.http.post("/api/alarm/" + alarmId + "/ack", {}).subscribe( function() { console.log("Alarm acknowledged"); // Force refresh du lieu }, function(err) { console.error("Ack failed:", err); } ); } // ==== Lay telemetry lich su tuy chinh ==== function fetchTelemetry(deviceId, keys, startTs, endTs, limit) { var url = "/api/plugins/telemetry/DEVICE/" + deviceId + "/values/timeseries"; url += "?keys=" + keys.join(","); url += "&startTs=" + startTs + "&endTs=" + endTs; url += "&limit=" + (limit || 1000) + "&orderBy=ASC"; return self.ctx.http.get(url); } // Goi: fetchTelemetry(deviceId, ["temperature","humidity"], Date.now()-3600000, Date.now(), 500) .subscribe(function(data) { console.log(data); }); |
| PHẦN 5: PATTERNS NÂNG CAO & BEST PRACTICES |
5. Patterns Hay Gap Va Best Practices
5.1 Pattern: Widget Skeleton – Khung Khởi Tạo Chuẩn
Đây là khung coe chuẩn nên áp dụng cho bất kỳ widget nào – đảm bảo khởi
tạo sạch sẽ, xử lý lỗi và cleanup đúng cách.
// ==== JAVASCRIPT -- Khung chuẩn cho mỗi widget ==== // Khai báo biến cấp module (không phải window) -- sẽ được giải phóng khi destroy var chart = null; var timer = null; var bcast = null; self.onInit = function() { var s = self.ctx.settings; // 1. Đọc settings, đặt giá trị mặc định self.ctx.$scope.title = s.title || "Widget"; self.ctx.$scope.unit = s.unit || ""; self.ctx.$scope.loading = true; self.ctx.$scope.error = null; self.ctx.$scope.hasData = false; // 2. Đăng ký hàm xử lý sự kiện self.ctx.$scope.onRefresh = function() { // Logic refresh... }; // 3. Khởi tạo thư viện (nếu cần) // chart = new Chart(...) self.ctx.detectChanges(); }; self.onDataUpdated = function() { try { if (!self.ctx.data || self.ctx.data.length === 0) { self.ctx.$scope.hasData = false; self.ctx.$scope.loading = false; self.ctx.detectChanges(); return; } // ... xử lý data ... self.ctx.$scope.hasData = true; self.ctx.$scope.loading = false; } catch(e) { console.error("[Widget] onDataUpdated error:", e); self.ctx.$scope.error = "Lỗi xử lý dữ liệu: " + e.message; } self.ctx.detectChanges(); }; self.onResize = function() { // Resize chart hoặc điều chỉnh layout if (chart) chart.resize(); }; self.onDestroy = function() { // QUAN TRỌNG: Clean up mọi thứ để tránh memory leak if (chart) { chart.destroy(); chart = null; } if (timer) { clearInterval(timer); timer = null; } if (bcast) { bcast.off("MY_EVENT"); bcast = null; } }; |
<!-- HTML -- Khung chuẩn phân biệt loading / no-data / content --> <div class="widget-root"> <!-- Đang tải --> <div *ngIf="ctx.$scope.loading" class="state-box"> <mat-spinner [diameter]="32"></mat-spinner> </div> <!-- Lỗi --> <div *ngIf="!ctx.$scope.loading && ctx.$scope.error" class="state-box error"> <mat-icon>error_outline</mat-icon> <span>{{ctx.$scope.error}}</span> </div> <!-- Không có dữ liệu --> <div *ngIf="!ctx.$scope.loading && !ctx.$scope.error && !ctx.$scope.hasData" class="state-box"> <mat-icon>info_outline</mat-icon> <span>Chưa có dữ liệu</span> </div> <!-- Nội dung chính --> <div *ngIf="!ctx.$scope.loading && !ctx.$scope.error && ctx.$scope.hasData" class="content"> <!-- ... nội dung widget ... --> </div> </div> |
5.2 Pattern: Null-Safe Data Reading
// ==== Hàm đọc giá trị an toàn -- tránh lỗi null/undefined/NaN ==== function safeVal(ctx, keyIndex, fallback) { try { var d = ctx.data[keyIndex]; if (!d || !d.data || d.data.length === 0) return fallback; var raw = d.data[0][1]; var num = parseFloat(raw); return isNaN(num) ? fallback : num; } catch(e) { return fallback; } } // ==== Hàm đọc giá trị theo tên key (linh hoạt hơn theo index) ==== function getValByKey(ctx, keyName, fallback) { var found = ctx.data.find(function(kd) { return kd.dataKey.name === keyName; }); if (!found || !found.data || found.data.length === 0) return fallback; var num = parseFloat(found.data[0][1]); return isNaN(num) ? fallback : num; } // ==== Sử dụng ==== self.onDataUpdated = function() { self.ctx.$scope.temp = safeVal(self.ctx, 0, null); self.ctx.$scope.humidity = safeVal(self.ctx, 1, null); self.ctx.$scope.pressure = getValByKey(self.ctx, "pressure", null); self.ctx.detectChanges(); }; |
5.3 Pattern: Override Title Và An Title Panel
// Đổi tiêu đề widget theo tên thiết bị đang xem self.onDataUpdated = function() { if (self.ctx.datasources && self.ctx.datasources[0]) { var deviceName = self.ctx.datasources[0].name; self.ctx.widgetTitle = deviceName; self.ctx.updateWidgetParams(); // BẮT BUỘC để cập nhật } }; // Ẩn title bar để tự vẽ header riêng trong HTML self.onInit = function() { self.ctx.hideTitlePanel = true; self.ctx.updateWidgetParams(); // Sau đó tự vẽ header trong HTML template }; |
5.4 Pattern: Responsive Theo Kích Thước Widget
// Debounce resize để tránh gọi quá nhiều lần var resizeTimer = null; self.onResize = function() { clearTimeout(resizeTimer); resizeTimer = setTimeout(function() { var w = self.ctx.width; var h = self.ctx.height; // Điều chỉnh font size theo chiều cao self.ctx.$scope.valueFontSize = Math.max(14, Math.min(48, h / 4)) + "px"; // Ẩn legend khi widget quá nhỏ self.ctx.$scope.showLegend = (w > 300 && h > 200); // Resize chart if (chart) chart.resize(); self.ctx.detectChanges(); }, 100); // Chờ 100ms sau lần resize cuối cùng }; // HTML: [style.font-size]="ctx.$scope.valueFontSize" // <div class="legend" *ngIf="ctx.$scope.showLegend">...</div> |
5.5 Pattern: Disable Widget Khi Đang Edit Dashboard
self.onEditModeChanged = function() { self.ctx.$scope.isEditing = self.ctx.isEdit; self.ctx.detectChanges(); }; // HTML: ẩn các nút control khi đang edit // <button [disabled]="ctx.$scope.isEditing" // (click)="ctx.$scope.sendRPC()"> // Bật thiết bị // </button> // Hoặc hiển thị overlay "đang chỉnh sửa" // <div *ngIf="ctx.$scope.isEditing" class="edit-overlay"> // <mat-icon>edit</mat-icon> Đang chỉnh sửa dashboard... // </div> |
5.6 Pattern: Dung ctx.widgetId De Tranh Conflict
Khi có nhiều widget cùng loại trên 1 dashboard, chúng dùng chung HTML
template. Nếu dùng ID cố định cho canvas/element, ác widget sẽ tranh
nhau. Luôn thêm ctx.widgetId vài ID.
<!-- HTML: Thêm widgetId vào ID của canvas/element --> <canvas id="myChart_{{ctx.widgetId}}"></canvas> <div id="gaugeContainer_{{ctx.widgetId}}"></div> // JavaScript: Đọc lại element bằng ID duy nhất đó self.onInit = function() { // Đợi DOM render xong mới lấy element setTimeout(function() { var canvasId = "myChart_" + self.ctx.widgetId; var canvas = document.getElementById(canvasId); if (!canvas) { console.error("Canvas không tìm thấy:", canvasId); return; } chart = new Chart(canvas, { /* config */ }); }, 0); }; |
| PHẦN 6: DEBUG, TROUBLESHOOTING & TOOLS |
6. Debug Và Xử Lý Lỗi Widget
6.1 Các Phương Pháp Debug
Phương Pháp 1: console.log – Đơn giản nhất
self.onInit = function() { console.log("[MyWidget] onInit called"); console.log("[MyWidget] settings:", self.ctx.settings); console.log("[MyWidget] datasources:", self.ctx.datasources); }; self.onDataUpdated = function() { console.log("[MyWidget] onDataUpdated, data length:", self.ctx.data.length); console.log("[MyWidget] full data:", JSON.stringify(self.ctx.data.map(function(d) { return { key: d.dataKey.name, count: d.data.length, latest: d.data[0] }; }))); }; |
Phương Pháp 2: debugger – Mạnh nhất
self.onDataUpdated = function() { debugger; // Trinh duyet se DUNG TAI DAY neu DevTools dang mo // Bam F12 truoc, sau do nhan Run tren Widget Editor // Trong tab Sources, ban co the: // - Xem gia tri cua moi bien bang cach hover chuot // - Goi lenh trong Console tab // - Buoc qua tung dong code (F10 = step over, F11 = step into) }; |
Phương Pháp 3: Hiển thị debug info trong widget
// Rất hữu ích khi test trên thiết bị thật mà không mở được DevTools self.onDataUpdated = function() { var debugLines = []; self.ctx.data.forEach(function(kd, i) { var latest = kd.data && kd.data[0] ? kd.data[0][1] : "N/A"; debugLines.push("[" + i + "] " + kd.dataKey.name + " = " + latest); }); self.ctx.$scope.debugInfo = debugLines.join(" | "); self.ctx.detectChanges(); }; |
6.2 Bảng Xử Lý Lỗi Thường Gặp
| Triệu chứng lỗi | Nguyên nhân | Cách sửa |
| UI không cập nhật dù data đã thay đổi trong JS | Quên gọi ctx.detectChanges() | Thêm ctx.detectChanges() sau mỗi lần thay đổi biến trong ctx.$scope ở onDataUpdated() hoặc callback. |
| Widget lỗi "Cannot read property of undefined" | Không kiểm tra null trước khi đọc ctx.data | Dùng pattern null-safe: if (!ctx.data || !ctx.data[0] || !ctx.data[0].data[0]) return; trước khi đọc data. |
| Nhiều widget cùng loại bị “chồng” canvas nhau | Dùng ID cố định cho canvas element | Đổi sang ID động: id="myChart_{{ctx.widgetId}}" và document.getElementById("myChart_"+self.ctx.widgetId). |
| broadcastService báo lỗi hoặc không hoạt động | Inject sai cách (dùng API cũ) | Dùng đúng cách mới: ctx.$scope.$injector.get(ctx.servicesMap.get("broadcastService")). |
| Thư viện external load thất bại / undefined | URL CDN sai hoặc không truy cập được từ server | Kiểm tra Network tab trong DevTools. Thử mở URL CDN trên trình duyệt. Đổi sang HTTPS. Self-host nếu không có internet. |
| ctx.controlApi báo undefined | Widget không được chọn loại "RPC Control" | Vào toolbar Widget Editor, đổi Widget Type sang Control widget. |
| ctx.timeWindow báo undefined | Widget không phải loại Time Series | timeWindow chỉ có trên Time series widget. Kiểm tra Widget Type. |
| Giá trị đọc được là NaN sau parseFloat() | Dữ liệu gốc là null, undefined, hoặc chuỗi không hợp lệ | Kiểm tra giá trị gốc bằng console.log trước khi parseFloat(). Dùng pattern: var n = parseFloat(raw); if (isNaN(n)) n = 0;. |
6.3 Checklist Truoc Khi Deploy Widget
| OK? | Hạng mục kiểm tra |
| [ ] | Đã test với datasource "Function" trong Widget Preview (F(x) trong preview) |
| [ ] | Xử lý trường hợp không có data (null/undefined check đầy đủ) |
| [ ] | onDestroy() cleanup tất cả: interval, chart instance, broadcast listeners |
| [ ] | ctx.detectChanges() được gọi sau mỗi lần thay đổi biến trong ctx.$scope |
| [ ] | Widget responsive: test ở chiều rộng 200px, 400px, 800px |
| [ ] | Settings Schema có giá trị mặc định hợp lý cho mỗi field |
| [ ] | Không có console.error khi mở DevTools trong quá trình sử dụng bình thường |
| [ ] | Canvas/element ID có dùng ctx.widgetId (nếu widget dùng canvas) |
| [ ] | External libraries được load từ HTTPS URL ổn định |
| [ ] | Widget hoạt động đúng khi refresh trang (không bị ghost state) |
| [ ] | Nút control bị disable khi ctx.isEdit = true (để tránh bấm nhầm khi edit) |
| [ ] | Đã export widget JSON và lưu backup |
6.4 Luồng Dữ Liệu Đầy Đủ -- 7 Bước Từ Thiết Bị Đến Màn Hình
| Bước | Mô tả |
| 1 | Thiết bị IoT gửi dữ liệu lên ThingsBoard qua MQTT/HTTP/CoAP → ThingsBoard lưu vào database Cassandra/PostgreSQL. |
| 2 | Widget subscription (IWidgetSubscription) trỏ ng dữ liệu theo time window và datasource config → ThingsBoard đẩy dữ liệu xuống. |
| 3 | onDataUpdated() được gọi → JavaScript đọc ctx.data, tính toán, xử lý ngưỡng, định dạng. |
| 4 | Gán kết quả vào ctx.$scope (ví dụ: ctx.$scope.temperature = 25.3). |
| 5 | Gọi ctx.detectChanges() → Angular kích hoạt change detection cycle. |
| 6 | Angular re-render HTML template → {{interpolation}}, *ngFor, *ngIf, [ngClass] được cập nhật trên DOM. |
| 7 | Người dùng thấy dữ liệu mới. Khi click/tương tác → (event) binding gọi hàm trong ctx.$scope → có thể gửi RPC qua controlApi. |
self.ctx Deep Dive -- ThingsBoard CE 4.2.1.1 https://thingsboard.io/docs/user-guide/contribution/ui/basic-widget-api/ |
- « Previous
- 1
- 2
- 3
- Next »