mercredi 4 mars 2020

Adding a custom variable to EmberRouter and then using it in another file

I recently tried extended the EmberRouter to include the following piece of information.

router.js

import EmberRouter from '@ember/routing/router';

const Router = EmberRouter.extend({
  lastVisitedURL: null,

  init() {
    this._super(...arguments);
    this.on('routeWillChange', () => {
      this._super(...arguments);
      this.lastVisitedURL = this.currentURL;
    });
  }

  // Router.map code (not important)
})

I would now like to extract lastVisitedURL from a controller file. However, I'm not sure how to do it. Some of the things I've tried include importing the EmberRouter directly (I.E.):

import Router from '../router';

export default Controller.extend({
   someFunction() {
     console.log(Router.lastVisitedURL); // returns undefined
   }
});

I'm not perfectly sure what the problem is with this approach, but it appears to be returning me some sort of other object or function that doesn't truly contain the state of the router.

So the next approach, that seems to be a little more accepted, was to try to use the RouterService object that I believe is meant to provide an API to the EmberRouter.

import Router from '../router';

export default Controller.extend({
   router: service(),

   someFunction() {
     console.log(this.router.currentURL) // returns undefined
   }
});

The problem I encountered with this solution though is that even though the routerService can store the state of the EmberRouter, it doesn't store my specific new variable. So I now need a way to add this specific pice of data to the RouterService as well as the EmberRouter.

I'm not really sure how to do this or if there is a better approach to the problem I'm trying to solve. Any thoughts appreciated!




Aucun commentaire:

Enregistrer un commentaire