繁体   English   中英

2个角度分量之间的变化检测

[英]change detection between 2 angular components

我有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都不会改变

您看不到立即更新,因为您正在使用DataService不同实例。 要使其正常工作,请确保具有一个服务实例。 为此,将providers数组放置在AppModule'sRootComponent's @NgModule装饰器中,如下所示,

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

并从两个单独的组件中删除providers: [DataService]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM