Ember 3.4路由中Location类的实例化、查找、注入及调用问题
Hey there! Let's break down why your initial approach to using the Location class isn't working, and walk through the correct ways to access and use its methods in your Ember 3.4 route.
Why Your Original Code Fails
First, let's look at the code that threw the error:
import Location from '@ember/routing/location'; // Inside an action method console.log(Location.getURL()); // Error: getURL is not a function
The core issue here is that getURL() is an instance method, not a static method of the Location class. Ember's Location is an abstract class—you can't call its methods directly on the class itself. Instead, Ember creates a concrete instance of a Location implementation (like history or hash location, based on your app's config) and manages this instance through its container system.
Correct Ways to Access the Location Instance
Here are the reliable, Ember-compliant ways to get the initialized Location instance in your route:
1. Use this.router.location (Your Working Approach)
You already discovered that this.router.location.getURL() works—and this is a totally valid, straightforward method. The router instance in your route has direct access to the Location instance Ember set up for your app. This is the simplest option if you're working within a route.
someAction() { console.log(this.router.location.getURL()); // This works perfectly! }
2. Look Up the Instance via Ember's Container
You can also fetch the Location instance directly from Ember's container using the lookup method. This is useful if you need access in places where the router isn't directly available, but it's just as valid in a route:
someAction() { const locationInstance = this.lookup('location:main'); console.log(locationInstance.getURL()); }
3. Inject the Location Instance (Dependency Injection)
Ember supports dependency injection (DI) to inject the Location instance into your route. This makes the instance available as a property on your route, which can feel cleaner if you need to use it in multiple places:
import Route from '@ember/routing/route'; import { inject } from '@ember/service'; export default Route.extend({ // Inject the pre-configured location instance location: inject(), someAction() { console.log(this.get('location').getURL()); } });
Key Takeaways
- Never call methods like
getURL()directly on the importedLocationclass—these methods only exist on initialized instances managed by Ember. - Ember handles the setup of the Location instance for you; your job is just to access it via the router, container lookup, or DI.
- All three methods above work reliably in Ember 3.4, so pick the one that fits your code style and needs best.
内容的提问来源于stack exchange,提问作者Slim

