Skip to content

Cannot use router.isActive fix #20954

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/@ember/routing/router-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,7 @@ class RouterService extends Service.extend(Evented) {
*/
isActive(...args: RouteArgs) {
let { routeName, models, queryParams } = extractRouteArgs(args);
this._router.setupRouter();
let routerMicrolib = this._router._routerMicrolib;

// When using isActive() in a getter, we want to entagle with the auto-tracking system
Expand Down
38 changes: 38 additions & 0 deletions packages/ember/tests/routing/router_service_test/isActive_test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Controller from '@ember/controller';
import { Component } from '@ember/-internals/glimmer';
import { RouterTestCase, moduleFor } from 'internal-test-helpers';
import Service, { service } from '@ember/service';

Expand Down Expand Up @@ -168,5 +169,42 @@ moduleFor(
assert.deepEqual(qp.queryParams, { sort: 'ascending' });
});
}

['@test RouterService#isActive works reliably during component rendering before router initialization'](assert) {
assert.expect(1);

// This simulates the scenario where isActive is called during component rendering
// before the router has been fully set up, which used to throw an error

let componentInstance;

this.addTemplate('parent.index', '{{foo-component}}');

this.addComponent('foo-component', {
ComponentClass: class extends Component {
@service('router')
routerService;

init() {
super.init();
componentInstance = this;
}

get isRouteActive() {
// This used to throw "Cannot read properties of undefined (reading 'isActiveIntent')"
// before setupRouter() was added to the isActive method
return this.routerService.isActive('parent.child');
}
},
template: `{{this.isRouteActive}}`,
});

return this.visit('/').then(() => {
// The test passes if no error is thrown during rendering
// and isActive returns a boolean value
assert.strictEqual(typeof componentInstance.isRouteActive, 'boolean',
'isActive should return a boolean value without throwing an error');
});
}
}
);
Loading