改变两个角度分量之间的检测

时间:2017-01-22 14:47:59

标签: angular

我有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;
  }
}

将此服务注入video-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都不会改变

1 个答案:

答案 0 :(得分:2)

您无法立即看到更新,因为您使用的是 DataService 的不同实例。要使其工作,请确保拥有一个服务实例。为此,请将 providers 数组放入 AppModule's RootComponent's {{1 装饰器,如下所示,

@NgModule

并从单个组件中删除 @NgModule({ ... ... providers: [DataService] ... })

相关问题