Ionic router caches views?

#1

Hey!

In our application, I’ve noticed that Ionic appears to go to a cached version of the view. How do I prevent this? ngOnInit and ngOnDestroy do not fire during these navigation events. In particular the login form does not reset state. It uses a FormGroup form built in ngOnInit.

The form requires the user to

  1. Input their username.
  2. Select the server to connect to.

Ionic presents this view in its cached (completed) form after the user logs out, when what I expect the user to see is a pristine form. As I stands, if a user wants to proceed then they have to manually clear and re-enter their choices of server and username.

How can I prevent or change this caching strategy?

52

In the above screenshot, the form presents in a valid and submittable state despite that the data is not valid.

  ngOnInit(): void {
    this.form = this.formBuilder.group(
      {
        username: [
          environment.credentials.username, [
            Validators.required,
            Validators.minLength(this.minUsernameLength)
          ]
        ],
        server: [
          undefined, [
            Validators.required
          ]
        ]
      },
      {
        asyncValidator: [
          ValidateUsername.exists(this.accountService)
        ]
      }
    );

    this.subscription = this.form.controls.server.valueChanges
    .pipe(filter(Boolean))
    .subscribe(server => this.servers.active(server));
  }
#2

This is a known Angular issue! Angular caches views in its routing stack. When you visit a page, you visit the cached version. Clearing the cache on logout is a common-pattern problem among Angular application. There are two broad solutions:

  1. Call Compiler#clearCache, confirmed as not working.
  2. On logout call window.location.reload() which, while a horrible hacky thing, works if you time it correctly.

Since I’m stuck with this problem I’ll investigate feeding app state data to the forms. Hopefully state.value === undefined will equal form.value === undefined.

Source references: