2017-01-22 13 views
1

ナビゲーション(トピックリストを表示)とビデオリスト(選択したものを表示)の2つのコンポーネントがあります。2つの角度成分の間の変化を検出

私がしたいことは、ナビゲーション要素をクリックすると、ビデオリストのタイトルが変更されることだけです。このコンポーネントの

navigation.component.ts

import { Component, OnInit } from '@angular/core'; 
import {DataService} from "../../../services/data.service"; 

@Component({ 
    selector: 'app-navigation', 
    templateUrl: './navigation.component.html', 
    styleUrls: ['./navigation.component.css'], 
    providers: [DataService] 
}) 
export class NavigationComponent implements OnInit { 
    allTopics: any; 
    mainTopics: any; 
    constructor(private data: DataService) { 
    this.allTopics  = this.data.getAllTopics().subscribe(data => { 
     this.allTopics = data; 
     this.mainTopics = Object.keys(data); 
    }); 
    } 

    setCurrentSelectedSubTopic(subTopic) { 
    this.data.setCurrentSelectedSubTopic(subTopic) 
    } 

    ngOnInit() { 
    } 
} 

私は、クリックアクションを持っている:

(click)="setCurrentSelectedSubTopic(subTopic)" 

私がクリックしたときに、私は良いにconsole.logを取得します。 この関数はサービスを更新します。

data.service.ts

import { Injectable }  from '@angular/core'; 
import { Observable }  from 'rxjs/Observable'; 
import { Http, Response } from '@angular/http'; 

@Injectable() 
export class DataService { 
    currentSelectedSubTopic: any; 
    constructor(private http: Http) {} 

    getAllTopics(): Observable<any> { 
    return this.http.get(`http://localhost:4200/getAllTopics`) 
     .map(res => res.json()) 
    } 

    setCurrentSelectedSubTopic(subTopic) { 
    this.currentSelectedSubTopic = subTopic; 
    } 
} 

このサービスは、ビデオlist.component.ts

import { Component, OnInit } from '@angular/core'; 
import { DataService } from '../../../services/data.service'; 

@Component({ 
    selector: 'app-video-list', 
    templateUrl: './video-list.component.html', 
    styleUrls: ['./video-list.component.css'], 
    providers: [DataService] 
}) 
export class VideoListComponent implements OnInit { 
    constructor(public data: DataService) { 

    } 

    ngOnInit() { 
    } 
} 

に注入され、それがされていないHTML:

<p> 
{{data.currentSelectedSubTopic ? data.currentSelectedSubTopic.Name : ''}} 
</p> 

どんな私はしようとしましたが、このhtmlは変更されません

答えて

2

DataServiceの異なるインスタンスを使用しているため、即時更新が表示されません。それを機能させるには、サービスのインスタンスを1つだけ用意してください。これを行うには、以下に示すように、

@NgModule({ 
    ... 
    ... 
    providers: [DataService] 
    ... 
}) 

providersアレイAppModule's又は@NgModuleでデコレータを入れて、個々の成分の両方からproviders: [DataService]を除去します。

+0

私はコンポーネントからプロバイダのプロパティを削除し、それが私のapp.moudule.tsにあることを確認し、私のクリックでは何も変わりません –

+1

ありがとう!それは今働く。問題が見つかりました! –

関連する問題