Exploring the possibilities of Server-Side Rendering in Angular (v4) to enhance SEO performance.
Everything runs smoothly until the introduction of resolve
on the route. The inclusion of resolve
leads to the HTML title
maintaining its original value when inspecting the source code.
Module Setup:
import {
Injectable,
ModuleWithProviders,
NgModule
} from '@angular/core';
import {
ActivatedRouteSnapshot,
Resolve,
Router,
RouterModule,
RouterStateSnapshot
} from '@angular/router';
import {
Observable
} from 'rxjs/Rx';
import {
ArticleComponent
} from './article.component';
import {
Article,
ArticlesService,
UserService,
SharedModule
} from '../shared';
@Injectable()
export class ArticleResolver implements Resolve < Article > {
constructor(
private articlesService: ArticlesService,
private router: Router,
private userService: UserService
) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): any {
return this.articlesService.get(route.params['slug'])
.catch((err) => this.router.navigateByUrl('/'));
}
}
const articleRouting: ModuleWithProviders = RouterModule.forChild([{
path: 'article/:slug',
component: ArticleComponent,
resolve: {
article: ArticleResolver
},
data: {
preload: true
}
}]);
@NgModule({
imports: [
articleRouting,
SharedModule
],
declarations: [
ArticleComponent
],
providers: [
ArticleResolver
]
}) export class ArticleModule {}
Component Implementation:
import {
Component,
OnInit
} from '@angular/core';
import {
ActivatedRoute,
Router,
} from '@angular/router';
import {
Title,
Meta
} from '@angular/platform-browser';
import {
AppComponent
} from '../app.component';
import {
Article,
} from '../shared';
@Component({
selector: 'article-page',
templateUrl: './article.component.html'
})
export class ArticleComponent implements OnInit {
article: Article;
constructor(
private route: ActivatedRoute,
private meta: Meta,
private title: Title
) {}
ngOnInit() {
this.route.data.subscribe(
(data: {
article: Article
}) => {
this.article = data.article;
}
);
this.title.setTitle(this.article.title);
}
}
Navigating through Angular SSR is a learning experience, so any pointers or advice are welcome.