簡體   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