Reputation: 239
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
Upvotes: 1
Views: 91
Reputation: 55443
You can't 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.
Upvotes: 2