简体   繁体   中英

In EmberJS how can you use transition data in a controller?

I am getting the transition data in the route js file like so:

beforeModel(transition) { console.log(transition)  }

And I want to use it in a function in my controller like this:

import Controller from '@ember/controller';

export default class ListingsController extends Controller {

    get pageTitle() {
        if (this.transition.targetName == 'foo') {
        return 'page title';

        }
      }

}

And then I want to display the result like this:

<h1>{{this.pageTitle}}</h1>

I cannot find a way to pass the transition data from the route to the controller. Any ideas?

While you technically can leverage the beforeModel to get the controller via this.controllerFor as @KathirMagaesh suggests, I wouldn't actually advocate for this solution. It's definitely not the normal or expected Ember pattern. Furthermore, if you look at the transition api , there is no reference to transition.targetName . If this works, this is private api and thus brittle.

If you need to change a property based on the current route, you should be using the public router service which provides some useful properties for this very purpose!

For example, in your controller you could have a computed property that leverages the router service to determine what the page title should be

import Controller from '@ember/controller';
import { computed } from '@ember/object';
import { inject } from '@ember/service';

// this injects the router service into our component via Ember's DI framework
router: inject(),
export default Controller.extend({
  pageTitle: computed('router.currentRouteName', function(){
     let currentRoute = this.router.currentRouteName;
     if(currentRoute === 'foo'){
        return 'page title';
     } 
     // do other stuff for other routes. 
  })
})

This leverages currentRouteName which is the period separated name like foo.bar . You can also also access the url via currentURL which would be /foo/bar

PS. Since I haven't used ES6 classes yet, I've provided the old style ember solution. You'll probably need to use the @computed decorator or @tracked where I'm using the computed function. I only know about the Octane ember style from RFCs and awesome blog posts but am not up to date with what's landed.

PPS. If you're on old ember, the current route name / URL properties are available on the application controller.

In the beforeModel hook use

this.controllerFor(currentrRouteName).set('transition', transition);

This will set transition property in controller of the current router .

For more on controllerFor()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM