Angular 2通过服务更改页面标题

Angular 2通过服务更改页面标题,angular,page-title,Angular,Page Title,我有一个页面组件,它通过服务加载内容。页面标题当前在ngOnInit中设置,但我想将其更改为使用通过服务接收的数据设置页面标题。服务接收到的JSON有一个“title”字段,其中包含页面标题的字符串 现在代码看起来像: import { Component, OnInit } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { GetPageService } from '../sha

我有一个页面组件,它通过服务加载内容。页面标题当前在ngOnInit中设置,但我想将其更改为使用通过服务接收的数据设置页面标题。服务接收到的JSON有一个“title”字段,其中包含页面标题的字符串

现在代码看起来像:

import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { GetPageService } from '../shared/get-page/get-page.service';

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

    data: any[] = [];
    errorMessage: string;

    constructor(
        private titleService: Title,
        public getPageService: GetPageService
    ) { }

    ngOnInit() {
        this.getPage();
        // line below should be replaced so that title come from getPage data
        this.titleService.setTitle('Sample Page Title');
    }

    getPage() {
        this.getPageService.getPage('capabilities')
            .subscribe(
                data => this.data = data,
                error => this.errorMessage = <any>error
            );

    }

}
从'@angular/core'导入{Component,OnInit};
从“@angular/platform browser”导入{Title};
从“../shared/get page/get page.service”导入{GetPageService};
@组成部分({
选择器:“应用程序功能”,
templateUrl:'./capabilities.component.html',
样式URL:['./capabilities.component.scss']
})
导出类功能组件在NIT上实现{
数据:任意[]=[];
错误消息:字符串;
建造师(
私人产权服务:产权,
公共getPageService:getPageService
) { }
恩戈尼尼特(){
这个是.getPage();
//应替换下面的行,以便标题来自getPage数据
this.titleService.setTitle(“示例页面标题”);
}
getPage(){
这个.getPageService.getPage('功能')
.订阅(
data=>this.data=data,
error=>this.errorMessage=错误
);
}
}

我已经尝试附加一个函数来订阅,但到目前为止,我只是得到了错误。如果您能给我提供正确的指导,我们将不胜感激。

请在
订阅()中设置标题。

getPage(){
这个.getPageService.getPage('功能')
.订阅(
(数据:任何)=>{
这个数据=数据;
//在这里设置标题。
this.titleService.setTitle(data.title);//或data['title']
},
error=>console.error(错误)
);
}

谢谢AF。这允许我访问titleService,但仍然会生成一个错误:如果我在“This.data=data”后面的控制台上记录var数据,则类型“string[]”上不存在属性“title”;它显示为一个对象。所以我不确定问题出在哪里。你能显示一下你日志中包含的对象吗?返回的对象是:{title:“Capabilities Page title”,heading:“Capabilities”,content:“content here.

”}当我将data.title更改为data['title']时,它可以工作。谢谢你的帮助。好的,好消息!那可能是打字稿的问题。在subscribe中,如果您将
any
类型添加到
data
,应该可以解决问题(我已经更新了答案)。