2017-01-22 94 views
1

我有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的不同实例。为了使它工作,请确保有一个服务实例。为了做到这一点,把providers阵列中AppModule's@NgModule装饰如以下所示,

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

和除去providers: [DataService]从两个单独的组件。

+0

因此我从组件中删除提供程序属性,并确保它在我的app.moudule.ts中,但仍然没有任何变化,我点击 –

+1

谢谢!它现在有效。发现问题了! –

相关问题