簡體   English   中英

使用angular 2 titleService和服務器端渲染調用setTitle時為500

[英]500 when calling setTitle using angular 2 titleService and server side rendering

我在使用angular 2和titleService進行服務器端渲染時遇到問題。

我的代碼看起來像這樣

import { Component } from '@angular/core';
import { BrowserModule, Title } from '@angular/platform-browser';
import { Router } from '@angular/router';

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [Title]
})

export class AppComponent {
    constructor(private titleService: Title) {
        titleService.setTitle("Setting the title...");
    }
}

使用客戶端渲染工作正常,但重新加載頁面時出現此錯誤:

例外:調用節點模塊失敗並顯示錯誤:TypeError:無法在字符串''上創建屬性'title'

有沒有想過為什么會這樣?

對於角度通用,不需要提供任何外部服務,因為它是內置的。(正如echonax在評論中所述。)

這個角度通用叉子的工作示例。 我猜你的角度通用版應該是一樣的。

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Meta, Title } from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  constructor(private _router: Router, private _meta: Meta, private _title: Title) { }

  ngOnInit() {
    this._router.events.subscribe((event) => {      
      if (event instanceof NavigationEnd) {
        switch (event.urlAfterRedirects) {
          case '/':
            this._title.setTitle('title goes here');
            this._meta.updateTag({ name: 'description', content: 'same goes for meta content' });
            break;
          case '/another-route':
            this._title.setTitle('Another title');
            this._meta.updateTag({ name: 'description', content: 'You get the idea' });
            break;

        }
      }
    });
  }
}

每次導航到新路線時,NavigationEnd都會負責設置新標題。

希望能幫助到你。

我想這可能是預期的,因為titleService與僅存在於瀏覽器中的元素交互。 當閱讀“Universal Gotchas”時,它顯然需要在執行此操作時檢查您是在客戶端還是在瀏覽器中。 我希望titleService可以處理這些事情。 但是檢查客戶是否解決了問題。

Se: https//github.com/angular/universal

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM