Complete the code to import the TransferState service in an Angular component.
import { Component } from '@angular/core'; import { [1] } from '@angular/platform-browser'; @Component({ selector: 'app-root', template: '<h1>Welcome</h1>' }) export class AppComponent {}
The TransferState service is imported from @angular/platform-browser to share data between server and client.
Complete the constructor to inject the TransferState service.
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) {} }
The TransferState service is injected with a variable name, commonly transferState.
Fix the error in setting a value in TransferState using makeStateKey.
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'); } }
The correct method to save data in TransferState is set.
Fill both blanks to retrieve data from TransferState safely.
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; } }
The get method retrieves data from TransferState. The second argument is the default value if no data exists, often null.
Fill all three blanks to create a TransferState key, set data, and then remove it.
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); } }
makeStateKey needs a string key like 'item'. Use set to save data and remove to delete it from TransferState.