Marc Rasmussen
Marc Rasmussen

Reputation: 20555

ionic page data does not update

So say i have page one:

This page contains multiple variables and a constructor. it could look something like this:

export class TestPage implements OnInit {

    testInt: number;
    testString: string;
    constructor(private someService: SomeService) {

    }

    ngOnInit() {
        this.testInt = this.someService.getInt();
        this.testString = this.someService.getLongText();
    }

}

Now when this page loads it correctly sets the values.

Now say that I change page and on this page, I change some of the values in the service.

When I then come pack to this TestPage it hasn't updated the values.

Does this have something to do with caching? or with push state?

How can I make sure that the page is "reloaded" ?

Upvotes: 0

Views: 162

Answers (1)

grizlizli
grizlizli

Reputation: 137

Try using RxJS.

@Injectable({...})
class SomeService {
    private _testInt: BehaviorSubject<number> = new BehaviorSubject<number>(0); // initial value 0

    setTestInt(value: number) {
        this._testInt.next(value);
    }

    getTestInt(): Observable<number> {
        return this._testInt.asObservable();
    }
}

@Component({...})
class TestPage implements OnInit {
    public testInt: number;
    public testInt$: Observable<number>;
    private subscription: Subscription;

    constructor(private someService: SomeService) {}

    ngOnInit() {
        // one way
        this.testInt$ = this.someService.getTestInt();

        // or another
        this.subscription = this.someService.getTestInt()
            .subscribe((value: number) => {
               this.testInt = value;
            });
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

in the HTML:

<p>{{ testInt }}</p>
<p>{{ testInt$ | async }}</p>

If you are subscribing to a Observable, make sure you unsubscribe after the usage (usually On Destroy lifecycle hook).

Async Pipe does that out of the box.

Or try the ionViewWillEnter lifecycle hook.

As you can see in the official documentation: ngOnInit will only fire each time the page is freshly created, but not when navigated back to the page.

For instance, navigating between each page in a tabs interface will only call each page's ngOnInit method once, but not on subsequent visits.

ngOnDestroy will only fire when a page "popped". link That means that Page is cached, yes. Assigning value On Init will set the value only the first time page is visited and therefore not updated.

Upvotes: 1

Related Questions