简体   繁体   中英

change detection between 2 angular components

i have 2 components - navigation (which shows topics list) and video-list (which shows the selected one).

all i want to do is that when i click on some navigation element, the video list title will change.

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() {
  }
}

on this component i have a click action:

(click)="setCurrentSelectedSubTopic(subTopic)"

when i click, i get a good console.log. this function update a service.

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

this service is injected to 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() {
  }
}

and it html is:

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

no matter what i tried to do, this html doesn't change

You cant see immediate update because you are using different instances of DataService . To make it work, make sure to have a single instance of your service. To do that, put providers array in AppModule's or RootComponent's @NgModule decorator as shown below,

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

and remove providers: [DataService] from both individual component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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