@greenie2600 wrote:
I have an app with two pages. One of them (
HardwareIntegrationSensorsPage
) subscribes to an observable (which happens to be BatteryStatus.onChange()).That subscriber updates a property on the component, and then calls
ChangeDetectorRef.detectChanges()
so the view will actually be updated.This works fine, as long as
HardwareIntegrationSensorsPage
is the very first page loaded by the app. If I navigate toOtherPage
and come back – or if I tweak my app so thatOtherPage
loads first – then my call to.detectChanges()
throws an error:ViewDestroyedError: Attempt to use a destroyed view: detectChanges
This confuses me, because the constructor for
HardwareIntegrationSensorsPage
runs each time the page is entered. Which (I would think) means it should get a freshChangeDetectorRef
.Relevant code:
import { Component, OnInit, OnDestroy, ChangeDetectorRef } from '@angular/core'; import { NavParams } from 'ionic-angular'; import { Subscription } from 'rxjs/Subscription'; import { BatteryStatus, BatteryStatusResponse } from '@ionic-native/battery-status'; import { Slide } from '../../models/slide'; @Component({ selector: 'page-hardware-integration-sensors', templateUrl: 'hardware-integration-sensors.html' }) export class HardwareIntegrationSensorsPage implements OnInit, OnDestroy { private slide: Slide; private batteryStatus_subscription: Subscription; private batteryStatus_response: BatteryStatusResponse = null; constructor( private cd: ChangeDetectorRef, public navParams: NavParams, private batteryStatus: BatteryStatus, ) { this.slide = this.navParams.get('slide'); } ngOnInit(): void { console.log('Subscribing to batteryStatus'); this.batteryStatus_subscription = this.batteryStatus.onChange().subscribe((response: BatteryStatusResponse) => { this.batteryStatus_response = response; this.cd.detectChanges(); // this line is causing the error }); } ngOnDestroy(): void { console.log('Unsubscribing from batteryStatus'); this.batteryStatus_subscription.unsubscribe(); } }
Any hints? I’m still pretty hazy on exactly how manual change detection is supposed to work. I suspect that
.detach()
and/or.reattach()
may be helpful here, but I don’t understand how I’m supposed to use them.
Posts: 2
Participants: 2