2017-02-16 5 views
1

서비스를 통해 콘텐츠를로드하는 페이지 구성 요소가 있습니다. 페이지 제목은 현재 ngOnInit에 설정되어 있지만 서비스를 통해받은 데이터로 페이지 제목을 설정하도록 변경하고 싶습니다. 서비스에서받은 JSON에는 페이지 제목 문자열이있는 "title"필드가 있습니다. 내가 구독하는 기능을 연결 시도했지만 지금까지 난 그냥 오류를 얻고있다서비스를 통한 각도 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", 내용 : "

내용은 여기

"} data.title을 데이터 [ 'title']로 변경하면 작동합니다. 이걸 도와 줘서 고마워. – lukemcd