使用路径解析进行角度服务器端渲染

时间:2017-10-04 02:31:11

标签: javascript angular typescript

我试图在Angular(v4)中使用服务器端渲染以允许更好的SEO。

在我的路线上添加resolve之前,事情按预期工作。添加resolve会导致HTML title在查看来源时保留其初始值。

我的模块:

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 {}

我的组件:

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);
  }
}

我是Angular SSR的新手,所以非常感谢任何指导。

2 个答案:

答案 0 :(得分:4)

不是订阅路线数据,而是从快照中检索结果,如下所示:

this.route.snapshot.data['article']

您还可能需要在ArticlesService中为模块注册providers

作为旁注,这个导入:

import {
  Observable
} from 'rxjs/Rx';

是一个RxJS反模式。请改为使用以下导入:

import {Observable} from 'rxjs/Observable';

答案 1 :(得分:0)

我发现我的主要服务是引用试图从window.localStorage返回身份验证令牌的辅助服务。

尝试访问客户端存储导致Angular SSR省略了我的组件的源代码生成。

感谢@Adam_P帮助我完成它!