1
我有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;
}
}
此服務被注入到視頻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不會改變
因此我從組件中刪除提供程序屬性,並確保它在我的app.moudule.ts中,但仍然沒有任何變化,我點擊 –
謝謝!它現在有效。發現問題了! –