Angular 5 Title服务未定义

时间:2018-02-21 12:56:03

标签: angular typescript title

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

在子模块中(我试图在这里添加服务和模块(BrowserModule))我有一个组件,我插入标题服务,但该服务未定义'。

模块

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

app模块

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

2 个答案:

答案 0 :(得分:3)

问题很常见:​​当一个类方法用作回调函数时,this在方法内部是不正确的。您应该使用箭头函数作为回调:

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

答案 1 :(得分:1)

好像你正在失去范围。 在process()范围内this不再代表您的类实例。

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

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