gpt4 book ai didi

Angular 5 标题服务未定义

转载 作者:搜寻专家 更新时间:2023-10-30 21:22:28 25 4
gpt4 key购买 nike

我尝试使用 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();
}
}

应用模块

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

最佳答案

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

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

关于Angular 5 标题服务未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48906512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com