我有一个页面组件,它通过服务加载内容。页面标题当前在ngOnInit中设置,但我想更改它以使用通过服务接收的数据设置页面标题。该服务收到的JSON标题为"标题为#34;带有页面标题字符串的字段。
现在代码看起来像:
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
);
}
}
我已经尝试附加一个函数来订阅,但到目前为止我只是得到错误。任何暗示我指向正确方向的提示都会非常感激。
答案 0 :(得分:2)
在subscribe()
:
getPage() {
this.getPageService.getPage('capabilities')
.subscribe(
(data: any) => {
this.data = data;
// Set the title here.
this.titleService.setTitle(data.title); // Or data['title']
},
error => console.error(error)
);
}