Search code examples
angularpage-title

Angular 2 change page title through service


I have a page component which loads content through a service. The page title is currently set in ngOnInit but I would like to change it to set the page title with data received through the service. The JSON received by the service has a "title" field with the string for the page title.

Right now the code looks like:

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

    }

}

I have tried attaching a function to subscribe but so far I am just getting errors. Any hints pointing me in the right direction would be much appreciated.


Solution

  • Set the title from within the 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)
            );
    
    }