Skip to content

Instantly share code, notes, and snippets.

@anthanh
Last active December 12, 2017 23:38
Show Gist options
  • Save anthanh/0b2c19068ba260ceb8d639f5556eaf91 to your computer and use it in GitHub Desktop.
Save anthanh/0b2c19068ba260ceb8d639f5556eaf91 to your computer and use it in GitHub Desktop.
Angular 5 with Universal and TransferState: TransferState Support
// app.component.ts
...
import { TransferState, makeStateKey } from '@angular/platform-browser';
const PHOTOS = makeStateKey('photos');
@Component({...})
export class AppComponent implements OnInit {
opened: boolean;
photos: any[];
constructor(private http: HttpClient, private state: TransferState) { }
ngOnInit() {
this.photos = this.state.get(PHOTOS, null as any);
if (!this.photos) {
this.http
.get('http://jsonplaceholder.typicode.com/photos?_limit=10')
.subscribe((data: any[]) => {
this.photos = data;
this.state.set(PHOTOS, data as any);
});
}
}
}
// app.module.ts
...
import { BrowserModule, BrowserTransferStateModule } from '@angular/platform-browser';
@NgModule({
...
imports: [
...
BrowserModule.withServerTransition({ appId: 'app' }),
BrowserTransferStateModule
]
})
export class AppModule { }
// app.server.module.ts
...
import { ServerModule, ServerTransferStateModule } from '@angular/platform-server';
@NgModule({
imports: [
...
ServerModule,
ServerTransferStateModule
],
bootstrap: [AppComponent],
})
export class AppServerModule { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment