Bird
Raised Fist0
Angularframework~10 mins

TransferState for data sharing in Angular - Interactive Code Practice

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
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the TransferState service in an Angular component.

Angular
import { Component } from '@angular/core';
import { [1] } from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  template: '<h1>Welcome</h1>'
})
export class AppComponent {}
Drag options to blanks, or click blank then click option'
AHttpClient
BTransferState
CRouter
DNgModule
Attempts:
3 left
💡 Hint
Common Mistakes
Importing HttpClient instead of TransferState
Importing from wrong Angular package
2fill in blank
medium

Complete the constructor to inject the TransferState service.

Angular
import { Component } from '@angular/core';
import { TransferState } from '@angular/platform-browser';

@Component({
  selector: 'app-data',
  template: '<p>Data component</p>'
})
export class DataComponent {
  constructor(private [1]: TransferState) {}
}
Drag options to blanks, or click blank then click option'
AtransferState
BhttpClient
Crouter
DstateService
Attempts:
3 left
💡 Hint
Common Mistakes
Using unrelated variable names like httpClient or router
Not using private keyword in constructor
3fill in blank
hard

Fix the error in setting a value in TransferState using makeStateKey.

Angular
import { makeStateKey, TransferState } from '@angular/platform-browser';

const DATA_KEY = makeStateKey<string>('data');

export class ExampleComponent {
  constructor(private transferState: TransferState) {}

  saveData() {
    this.transferState.[1](DATA_KEY, 'Hello World');
  }
}
Drag options to blanks, or click blank then click option'
Aput
Badd
Cset
Dstore
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'put' or 'add' which do not exist
Using 'store' which is not a method
4fill in blank
hard

Fill both blanks to retrieve data from TransferState safely.

Angular
import { makeStateKey, TransferState } from '@angular/platform-browser';

const USER_KEY = makeStateKey<string>('user');

export class UserComponent {
  constructor(private transferState: TransferState) {}

  getUser() {
    const user = this.transferState.[1](USER_KEY, [2]);
    return user;
  }
}
Drag options to blanks, or click blank then click option'
Aget
Bnull
Cundefined
D''
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'set' instead of 'get' to retrieve data
Using 'undefined' or empty string as default instead of null
5fill in blank
hard

Fill all three blanks to create a TransferState key, set data, and then remove it.

Angular
import { makeStateKey, TransferState } from '@angular/platform-browser';

const ITEM_KEY = makeStateKey<string>([1]);

export class ItemComponent {
  constructor(private transferState: TransferState) {}

  updateItem() {
    this.transferState.[2](ITEM_KEY, 'Item Data');
    this.transferState.[3](ITEM_KEY);
  }
}
Drag options to blanks, or click blank then click option'
A'item'
Bset
Cremove
D'data'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong string key or missing quotes
Using 'get' instead of 'set' to save data
Using 'clear' instead of 'remove' to delete data

Practice

(1/5)
1. What is the main purpose of Angular's TransferState service?
easy
A. To handle routing between Angular modules
B. To share data between server and client to avoid duplicate HTTP requests
C. To store user preferences in local storage
D. To manage component state within a single client session

Solution

  1. Step 1: Understand TransferState's role

    TransferState is designed to transfer data fetched on the server to the client to prevent refetching.
  2. Step 2: Compare options

    Only To share data between server and client to avoid duplicate HTTP requests correctly describes this purpose; others describe unrelated features.
  3. Final Answer:

    To share data between server and client to avoid duplicate HTTP requests -> Option B
  4. Quick Check:

    TransferState purpose = share data server-client [OK]
Hint: Remember TransferState avoids duplicate data fetching [OK]
Common Mistakes:
  • Confusing TransferState with client-only state management
  • Thinking it manages routing or local storage
  • Assuming it only works on the client side
2. Which of the following is the correct way to create a state key using makeStateKey in Angular?
easy
A. const KEY = makeStateKey('userData');
B. const KEY = new StateKey('userData');
C. const KEY = createStateKey('userData');
D. const KEY = StateKey('userData');

Solution

  1. Step 1: Recall correct syntax for state key creation

    Angular provides the makeStateKey function to create keys, not a constructor or other function.
  2. Step 2: Validate options

    Only const KEY = makeStateKey('userData'); uses makeStateKey correctly with proper syntax.
  3. Final Answer:

    const KEY = makeStateKey('userData'); -> Option A
  4. Quick Check:

    Use makeStateKey() to create keys [OK]
Hint: Use makeStateKey('name') exactly to create keys [OK]
Common Mistakes:
  • Using new keyword with StateKey
  • Calling non-existent createStateKey function
  • Omitting the function call parentheses
3. Given this Angular code snippet on the server:
const USER_KEY = makeStateKey('user');
this.transferState.set(USER_KEY, { name: 'Alice', age: 30 });
What will this.transferState.get(USER_KEY, null) return on the client?
medium
A. null
B. undefined
C. { name: 'Alice', age: 30 }
D. An error because data cannot be retrieved on client

Solution

  1. Step 1: Understand data flow with TransferState

    Data set on the server with set is serialized and available on the client.
  2. Step 2: Retrieve data on client

    Calling get with the same key returns the stored object, not null or error.
  3. Final Answer:

    { name: 'Alice', age: 30 } -> Option C
  4. Quick Check:

    Server set data = client get data [OK]
Hint: Data set on server is available on client with same key [OK]
Common Mistakes:
  • Expecting null because of second argument
  • Thinking data is undefined on client
  • Assuming an error occurs when accessing TransferState on client
4. Identify the error in this Angular code using TransferState:
const DATA_KEY = makeStateKey('data');
this.transferState.set(DATA_KEY, { value: 42 });
const data = this.transferState.get('DATA_KEY', null);
medium
A. The key passed to get() should be the StateKey object, not a string
B. The set() method cannot store objects, only strings
C. makeStateKey should not be used for keys
D. transferState cannot be used outside ngOnInit

Solution

  1. Step 1: Check key usage in get()

    The get method requires the same StateKey object used in set, not a string.
  2. Step 2: Validate other statements

    Objects can be stored, makeStateKey is correct, and transferState can be used anytime in component lifecycle.
  3. Final Answer:

    The key passed to get() should be the StateKey object, not a string -> Option A
  4. Quick Check:

    Use same StateKey object for set and get [OK]
Hint: Pass StateKey object, not string, to get() [OK]
Common Mistakes:
  • Passing string instead of StateKey to get()
  • Thinking set() only accepts strings
  • Misunderstanding when transferState can be used
5. You want to optimize your Angular Universal app by sharing a list of products fetched on the server with the client using TransferState. Which approach correctly implements this?
hard
A. On client, set products in TransferState and then fetch from server.
B. On client, always fetch products via HTTP and ignore TransferState.
C. On server, store products in a global variable and access it directly on client.
D. On server, fetch products and call transferState.set(PRODUCTS_KEY, products). On client, retrieve with transferState.get(PRODUCTS_KEY, []) before making HTTP call.

Solution

  1. Step 1: Understand TransferState usage for server-client data sharing

    Data fetched on server should be stored in TransferState to avoid client refetch.
  2. Step 2: Apply correct flow

    On server, fetch products and call transferState.set(PRODUCTS_KEY, products). On client, retrieve with transferState.get(PRODUCTS_KEY, []) before making HTTP call. correctly sets data on server and retrieves on client before HTTP call, optimizing performance.
  3. Step 3: Eliminate incorrect options

    Options B, C, and D misuse TransferState or data flow concepts.
  4. Final Answer:

    On server, fetch products and call transferState.set(PRODUCTS_KEY, products). On client, retrieve with transferState.get(PRODUCTS_KEY, []) before making HTTP call. -> Option D
  5. Quick Check:

    Server sets data, client gets data before HTTP [OK]
Hint: Set on server, get on client before HTTP call [OK]
Common Mistakes:
  • Fetching data again on client ignoring TransferState
  • Trying to share data via global variables
  • Setting data on client instead of server