2017-02-16 4 views
1

サービスからコンテンツを読み込むページコンポーネントがあります。ページタイトルは現在ngOnInitで設定されていますが、サービスを介して受信したデータでページタイトルを設定するように変更したいと考えています。サービスで受け取ったJSONには、ページタイトルの文字列を含む「タイトル」フィールドがあります。角2のページのタイトルからサービスへの変更

今のコードは次のようになります。

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

    } 

} 

私が購読する機能を付加しようとしているが、これまでのところ、私はちょうど、エラーを取得しています。正しい方向で私を指し示すヒントは、非常に高く評価されます。

答えて

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

} 
+0

おかげでAF。これによりtitleServiceにアクセスできますが、エラーが発生します。 プロパティ 'title'が型 'string []'に存在しません 「this.data = data;オブジェクトとして表示されます。だから私はその問題が何であるか分かりません。 – lukemcd

+0

ログに記録されているオブジェクトを表示してください。 – AngularChef

+0

返されるオブジェクトは次のとおりです。{title: "Capabilities Page title"、見出し: "Capabilities"、コンテンツ: "

Content here。

"} data.titleをdata [title]に変更すると動作します。これで助けていただきありがとうございます。 – lukemcd

関連する問題