Bird
Raised Fist0
Angularframework~10 mins

Resolver for pre-fetching data in Angular - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Resolver for pre-fetching data
Route Activated
Resolver Called
Fetch Data (async)
Data Ready?
NoWait
Yes
Pass Data to Component
Component Renders with Data
When a route activates, Angular calls the resolver to fetch data before the component loads. The route waits until data is ready, then passes it to the component.
Execution Sample
Angular
export const routes = [
  { path: 'user/:id', component: UserComponent, resolve: { user: UserResolver } }
];
Defines a route that uses a resolver to fetch user data before loading UserComponent.
Execution Table
StepActionResolver StateData FetchedComponent State
1Route 'user/42' activatedNot startedNoneNot loaded
2Resolver UserResolver calledFetchingNoneNot loaded
3Fetching user data asyncFetchingNoneNot loaded
4User data receivedCompletedUser{id:42, name:'Alice'}Not loaded
5Data passed to UserComponentCompletedUser{id:42, name:'Alice'}Loading
6UserComponent renders with dataCompletedUser{id:42, name:'Alice'}Loaded with data
7Route fully loadedCompletedUser{id:42, name:'Alice'}Displayed
💡 Data fetched and component rendered, route loading complete.
Variable Tracker
VariableStartAfter Step 2After Step 4After Step 6Final
resolverStateNot startedFetchingCompletedCompletedCompleted
fetchedDataNoneNoneUser{id:42, name:'Alice'}User{id:42, name:'Alice'}User{id:42, name:'Alice'}
componentStateNot loadedNot loadedNot loadedLoaded with dataDisplayed
Key Moments - 3 Insights
Why does the route wait before loading the component?
Because the resolver fetches data asynchronously first (see execution_table step 3 and 4). The route waits until data is ready to ensure the component has what it needs.
What happens if the resolver fails to fetch data?
The route can be configured to handle errors or redirect. But by default, the component won't load until the resolver completes or errors out (not shown in this trace).
How does the component access the resolved data?
The resolved data is passed via the route's data property and can be accessed inside the component (see execution_table step 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the resolverState at step 3?
ANot started
BCompleted
CFetching
DError
💡 Hint
Check the 'Resolver State' column at step 3 in the execution_table.
At which step does the component start rendering with data?
AStep 6
BStep 5
CStep 4
DStep 7
💡 Hint
Look for 'Component renders with data' in the 'Action' column of execution_table.
If the resolver took longer to fetch data, which step would be delayed?
AStep 2
BStep 3
CStep 5
DStep 7
💡 Hint
Refer to the 'Fetching user data async' action in execution_table step 3.
Concept Snapshot
Resolver pre-fetches data before route loads.
Route waits for resolver to complete.
Data passed to component via route data.
Component renders only after data ready.
Helps avoid loading states inside component.
Full Transcript
When Angular activates a route with a resolver, it first calls the resolver to fetch data asynchronously. The route waits until the resolver finishes fetching data. Once data is ready, it passes the data to the component. Then the component renders with the data available. This ensures the component does not load without the necessary data. The resolver state changes from 'Not started' to 'Fetching' to 'Completed' as data is fetched. The component state changes from 'Not loaded' to 'Loaded with data' after data is passed. This flow helps avoid showing empty or loading states inside the component by pre-fetching data during routing.

Practice

(1/5)
1. What is the main purpose of a Resolver in Angular routing?
easy
A. To handle user authentication during navigation
B. To fetch data before the route loads so the page shows complete information
C. To define the layout of the page components
D. To manage CSS styles for routed components

Solution

  1. Step 1: Understand Resolver role

    Resolvers are designed to fetch data before a route activates, ensuring the page has all needed data upfront.
  2. Step 2: Compare options

    Only To fetch data before the route loads so the page shows complete information describes this pre-fetching behavior. Other options describe unrelated tasks.
  3. Final Answer:

    To fetch data before the route loads so the page shows complete information -> Option B
  4. Quick Check:

    Resolver purpose = pre-fetch data [OK]
Hint: Resolvers fetch data before route loads to avoid empty pages [OK]
Common Mistakes:
  • Confusing resolvers with guards for authentication
  • Thinking resolvers manage styles or layouts
  • Assuming resolvers run after the component loads
2. Which syntax correctly defines a Resolver service in Angular?
easy
A. export class DataResolver implements Resolve { resolve(): Data { return this.service.getData(); } }
B. export class DataResolver { fetch(route: ActivatedRouteSnapshot): Data { return this.service.getData(); } }
C. export class DataResolver implements Resolve<Data> { resolve(route: ActivatedRouteSnapshot): Observable<Data> { return this.service.getData(); } }
D. export class DataResolver implements Resolve<Data> { getData(route: ActivatedRouteSnapshot): Data { return this.service.getData(); } }

Solution

  1. Step 1: Check Resolver interface implementation

    The Resolver must implement Resolve<T> and define a resolve method with route parameter returning Observable or Promise.
  2. Step 2: Validate method signature

    export class DataResolver implements Resolve<Data> { resolve(route: ActivatedRouteSnapshot): Observable<Data> { return this.service.getData(); } } correctly implements Resolve<Data> with resolve(route: ActivatedRouteSnapshot): Observable<Data>. Others miss interface, method name, or return type.
  3. Final Answer:

    export class DataResolver implements Resolve<Data> { resolve(route: ActivatedRouteSnapshot): Observable<Data> { return this.service.getData(); } } -> Option C
  4. Quick Check:

    Resolver syntax = implements Resolve<T> + resolve() [OK]
Hint: Resolver must implement Resolve<T> and have resolve(route) method [OK]
Common Mistakes:
  • Missing the Resolve interface implementation
  • Using wrong method name instead of resolve
  • Returning data directly instead of Observable or Promise
3. Given this resolver code snippet, what will be the resolved data type when navigating to the route?
export class UserResolver implements Resolve<User> {
  constructor(private userService: UserService) {}
  resolve(route: ActivatedRouteSnapshot): Observable<User> {
    const id = route.paramMap.get('id')!;
    return this.userService.getUserById(id);
  }
}
medium
A. A Promise resolving to a User ID string
B. A plain string representing the user ID
C. An array of User objects
D. A User object wrapped in an Observable

Solution

  1. Step 1: Analyze resolve method return type

    The resolve method returns this.userService.getUserById(id), which returns Observable<User> as per signature.
  2. Step 2: Understand data type returned

    The resolved data is a User object wrapped inside an Observable, not a string or array.
  3. Final Answer:

    A User object wrapped in an Observable -> Option D
  4. Quick Check:

    Resolver returns Observable<User> [OK]
Hint: Resolver returns Observable of the specified data type [OK]
Common Mistakes:
  • Confusing the route param with resolved data
  • Assuming it returns a Promise or plain value
  • Thinking it returns an array instead of single object
4. Identify the error in this resolver code:
export class ProductResolver implements Resolve<Product> {
  constructor(private productService: ProductService) {}
  resolve(route: ActivatedRouteSnapshot): Product {
    const id = route.paramMap.get('id')!;
    this.productService.getProduct(id).subscribe(product => {
      return product;
    });
  }
}
medium
A. The resolve method returns void instead of Product or Observable<Product>
B. The subscribe method is missing a callback function
C. The constructor is missing dependency injection
D. The route parameter 'id' is not accessed correctly

Solution

  1. Step 1: Check resolve method return type

    The resolve method declares it returns Product but actually returns nothing because subscribe is asynchronous and returns void.
  2. Step 2: Understand correct return for resolver

    Resolvers must return Observable<Product> or Promise<Product>, not void. Using subscribe inside resolve breaks this contract.
  3. Final Answer:

    The resolve method returns void instead of Product or Observable<Product> -> Option A
  4. Quick Check:

    Resolvers must return Observable or Promise, not void [OK]
Hint: Never subscribe inside resolve; return Observable or Promise directly [OK]
Common Mistakes:
  • Using subscribe inside resolve instead of returning Observable
  • Returning wrong data type from resolve
  • Ignoring asynchronous nature of data fetching
5. You want to pre-fetch user profile and user settings before loading a route. How can you combine two resolvers to achieve this in Angular?
hard
A. Use multiple resolvers in the route config with different keys, then access both in the component
B. Create one resolver that calls both services and merges data into one object
C. Call one resolver inside another resolver's resolve method
D. Use a guard to fetch data instead of resolvers

Solution

  1. Step 1: Understand Angular route resolver configuration

    Angular allows multiple resolvers in route config by assigning each resolver to a unique key in the 'resolve' object.
  2. Step 2: Access resolved data in component

    The component can then access both resolved data objects via ActivatedRoute's data property using the keys.
  3. Step 3: Evaluate other options

    Create one resolver that calls both services and merges data into one object is possible but less modular. Call one resolver inside another resolver's resolve method is not standard practice. Use a guard to fetch data instead of resolvers uses guards, which are not for data pre-fetching.
  4. Final Answer:

    Use multiple resolvers in the route config with different keys, then access both in the component -> Option A
  5. Quick Check:

    Multiple resolvers = multiple keys in route config [OK]
Hint: Assign multiple resolvers with keys in route config [OK]
Common Mistakes:
  • Trying to chain resolvers inside each other
  • Merging data manually instead of using multiple resolvers
  • Using guards instead of resolvers for data fetching