Mam 2 komponenty - nawigację (która pokazuje listę tematów) i listę wideo (która pokazuje wybraną).
wszystko, co chcę zrobić, to to, że kiedy kliknę jakiś element nawigacyjny, tytuł listy filmów zmieni się.
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() {
}
}
na tym komponencie mam akcję kliknięcia:
(click)="setCurrentSelectedSubTopic(subTopic)"
kiedy klikam, otrzymuję dobry console.log. ta funkcja aktualizuje usługę.
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;
}
}
ta usługa jest wprowadzana do 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() {
}
}
i html to:
<p>
{{data.currentSelectedSubTopic ? data.currentSelectedSubTopic.Name : ""}}
</p>
bez względu na to, co próbowałem zrobić, ten HTML nie zmienia się
Odpowiedzi:
2 dla odpowiedzi № 1Nie można zobaczyć natychmiastowej aktualizacji, ponieważ używasz różnych instancji DataService
. Aby działało, upewnij się, że masz jedną instancję swojej usługi. Aby to zrobić, włóż providers
tablica w AppModule"s
lub RootComponent"s
@NgModule
dekorator, jak pokazano poniżej,
@NgModule({
...
...
providers: [DataService]
...
})
i usuń providers: [DataService]
z obu poszczególnych elementów.