Angular 5 标题服务未定义

Angular 5 Title service is undefined

我尝试使用 BrowserModule 更改页面标题。我在应用程序模块中添加了 BrowserModule 和 Title,如下所示:https://angular.io/guide/set-document-title

在 child 模块中(我也尝试在此处添加服务和模块 (BrowserModule))我有一个组件,我在其中插入标题服务,但该服务是 'undefined'。

模块

import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { RouterModule, Routes } from "@angular/router";

import { ProductService } from "../../services/Product";

import { ProductComponent } from "../../components/product/component";
import { ProductResolve } from "../../components/product/resolve";

const routes: Routes =
[
    {
        path: "produs/:url",
        component: ProductComponent,
        resolve:
        {
            Product: ProductResolve,
        },
    },
];

@NgModule({
    imports:
    [
        CommonModule,
        RouterModule.forChild(routes),
    ],
    providers:
    [
        ProductResolve,
        ProductService,
    ],
    declarations:
    [
        ProductComponent,
    ],
    exports:
    [
        RouterModule,
        ProductComponent,
    ],
})
export class ProductModule { }

组件:

import { Component, OnInit, OnDestroy } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { Product } from "../../services/Product";
import { Title } from '@angular/platform-browser';

@Component({
    templateUrl: "../../templates/product/component.html",
    styleUrls: [
        "../../sass/product/component.scss",
    ]
})

export class ProductComponent implements OnInit, OnDestroy
{
    private Subscribe: any;

    constructor(private titleService: Title, private Route: ActivatedRoute)
    {

    }

    ngOnInit()
    {
        this.Subscribe = this.Route.data.subscribe(this.process);
    }

    private process(product: Product)
    {
        //console.log(this.title);

        //this.titleService.setTitle(product.Title);
    }

    ngOnDestroy()
    {
        this.Subscribe.unsubscribe();
    }
}

应用模块

import { BrowserModule, Title } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
...

@NgModule({
    declarations: [
        ...
    ],
    imports: [
        ...
        BrowserModule,

    ],
    providers: [LoadingScreenService, Title],
    bootstrap: [AppComponent],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class AppModule { }

问题很普遍:当class方法作为回调函数时,方法内部的this不正确。您应该使用箭头函数作为回调:

this.Subscribe = this.Route.data.subscribe((product: Product) => {
    this.process(product);
});

您似乎失去了瞄准镜。 在 process() 范围内 this 不再代表您的 class 实例。

添加 .bind(this) 应该可以解决您的问题。

this.Subscribe = this.Route.data.subscribe(this.process.bind(this));