-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSSR-Hybrid-Rendering-Examples
More file actions
291 lines (240 loc) · 7.05 KB
/
SSR-Hybrid-Rendering-Examples
File metadata and controls
291 lines (240 loc) · 7.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
// SSR & Hybrid Rendering Examples
// Example 1: Mock Server Setup (Simplified for Demo)
// app.ts
import { Component, Injectable, NgModule, Inject, PLATFORM_ID } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { RouterModule, Routes, provideRouter, CanActivate } from '@angular/router';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TransferState, makeStateKey, StateKey } from '@angular/platform-browser';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { signal } from '@angular/core';
// Mock Server Setup (Simplified for Demo)
declare const require: any;
const express = typeof require === 'function' ? require('express') : null;
const helmet = typeof require === 'function' ? require('helmet') : null;
// Mock Data Keys for TransferState
const DATA_KEY: StateKey<any> = makeStateKey('serverData');
const CMS_DATA_KEY: StateKey<any> = makeStateKey('cmsData');
const USER_DATA_KEY: StateKey<any> = makeStateKey('userData');
// Mock Auth Service
@Injectable({ providedIn: 'root' })
export class AuthService {
private loggedIn = false;
login() { this.loggedIn = true; }
logout() { this.loggedIn = false; }
isAuthenticated() { return this.loggedIn; }
}
// Example 1: Basic SSR Setup Component
@Component({
selector: 'app-home',
standalone: true,
template: `
<h2>Home (SSR Enabled)</h2>
<p>Welcome to SSR Demo</p>
`
})
export class HomeComponent {}
// Example 2: TransferState Service
@Injectable({ providedIn: 'root' })
export class DataService {
constructor(
private http: HttpClient,
private transferState: TransferState,
@Inject(PLATFORM_ID) private platformId: Object
) {}
getData(): Observable<any> {
if (this.transferState.hasKey(DATA_KEY)) {
return of(this.transferState.get(DATA_KEY, null)); // Example 14
} else {
return this.http.get('https://api.example.com/data').pipe(
tap(data => {
if (isPlatformServer(this.platformId)) {
this.transferState.set(DATA_KEY, data);
}
})
);
}
}
}
// Example 3: Authentication with Cookies
@Component({
selector: 'app-login',
standalone: true,
template: `
<h2>Login</h2>
<button (click)="login()">Login</button>
`
})
export class LoginComponent {
constructor(
private authService: AuthService,
private http: HttpClient,
private router: Router
) {}
login() {
this.authService.login();
this.http.post('/api/auth/login', {}, { withCredentials: true }).subscribe(() => {
this.router.navigate(['/dashboard']); // Example 15
});
}
}
// Example 4: Dynamic API Content with SSR
@Component({
selector: 'app-blog',
standalone: true,
template: `
<h2>Blog (Dynamic SSR)</h2>
<div *ngFor="let post of posts">{{ post.title }}</div>
`
})
export class BlogComponent {
posts: any[] = [];
constructor(private dataService: DataService) {
this.dataService.getData().subscribe(data => {
this.posts = data; // Example 16
});
}
}
// Example 5: Hybrid Rendering with CSR Guard
@Injectable({ providedIn: 'root' })
export class NoSSRGuard implements CanActivate {
constructor(@Inject(PLATFORM_ID) private platformId: Object) {}
canActivate(): boolean {
return isPlatformBrowser(this.platformId); // Example 18
}
}
@Component({
selector: 'app-dashboard',
standalone: true,
template: `
<h2>Dashboard (CSR Only)</h2>
<p>Interactive Content</p>
`
})
export class DashboardComponent {
ngOnInit() {
if (typeof window !== 'undefined') {
document.getElementById('demo')?.classList.add('active'); // Example 19
}
}
}
// Example 6: CMS Integration
@Injectable({ providedIn: 'root' })
export class CmsService {
constructor(
private transferState: TransferState,
private http: HttpClient,
@Inject(PLATFORM_ID) private platformId: Object
) {}
getData(): any {
if (this.transferState.hasKey(CMS_DATA_KEY)) {
return this.transferState.get(CMS_DATA_KEY, []); // Example 20
} else {
return this.http.get('https://cms.example.com/posts').pipe(
tap(data => {
if (isPlatformServer(this.platformId)) {
this.transferState.set(CMS_DATA_KEY, data);
}
})
);
}
}
}
@Component({
selector: 'app-cms-content',
standalone: true,
template: `
<h2>CMS Content</h2>
<div *ngFor="let post of posts">{{ post.title }}</div>
`
})
export class CmsContentComponent {
posts: any[] = [];
constructor(private cmsService: CmsService) {
this.cmsService.getData().subscribe(data => {
this.posts = data;
});
}
}
// Example 7: Hydration Demo (Simplified)
@Component({
selector: 'app-hero',
standalone: true,
template: `
<h2>Hero (Partial Hydration)</h2>
<p>{{ title() }}</p>
<button (click)="increment()">Increment</button>
`
})
export class HeroComponent {
title = signal('Welcome to Angular SSR'); // Example 21 & 24
increment() {
this.title.update(value => value + '!');
}
}
// Main App Component
@Component({
selector: 'app-root',
standalone: true,
imports: [
RouterModule,
HomeComponent,
LoginComponent,
BlogComponent,
DashboardComponent,
CmsContentComponent,
HeroComponent
],
template: `
<h1>Angular SSR & Hybrid Rendering Demo</h1>
<nav>
<a routerLink="/home">Home (SSR)</a>
<a routerLink="/login">Login</a>
<a routerLink="/blog">Blog (SSR)</a>
<a routerLink="/dashboard">Dashboard (CSR)</a>
<a routerLink="/cms">CMS (SSR)</a>
<a routerLink="/hero">Hero (Hydration)</a>
</nav>
<router-outlet></router-outlet>
`
})
export class AppComponent {}
// Routes Definition
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: 'blog', component: BlogComponent },
{ path: 'dashboard', component: DashboardComponent, canActivate: [NoSSRGuard] },
{ path: 'cms', component: CmsContentComponent },
{ path: 'hero', component: HeroComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
// Mock Server Setup (Simplified - Not Fully Functional in Single File)
if (typeof express === 'function') {
const app = express();
const distFolder = 'dist/browser';
app.use(helmet());
app.use(express.static(distFolder, { maxAge: '1y' }));
app.get('*', (req, res) => {
res.render('index.html', { req, providers: [
{ provide: 'CMS_DATA', useValue: [{ title: 'Mock CMS Post' }] }
]});
});
// Example 8: Simplified server.ts snippet
app.set('view engine', 'html');
app.set('views', distFolder);
app.listen(4000, () => console.log('SSR Server running on http://localhost:4000'));
}
// Bootstrap the Application
bootstrapApplication(AppComponent, {
providers: [
provideRouter(routes),
{ provide: HttpClient, useValue: { get: () => of([{ title: 'Mock Data' }]) } }, // Mock HttpClient
DataService,
AuthService,
CmsService,
NoSSRGuard
]
}).catch(err => console.error(err));