На самом деле есть две проблемы, с которыми я сталкиваюсь. Я перекручивание через массив значений и нужноAngular2: Установить класс CSS из Observable
- установить имя класса в зависимости от наблюдаемой переменной из дочернего компонента.
- переоценить класс, как только изменяется дочерняя переменная.
location.component.ts
import { Component, Input } from '@angular/core';
import { BusinessLocation, SpecialDays, RegularHours } from './location';
import { DbService } from './db-service.component';
@Component({
selector: '[data-locations]',
templateUrl: 'app/location.component.html',
providers: [DbService]
})
export class LocationComponent {
locations:BusinessLocation[];
selectedLocationId:Number;
constructor(private api:DbService){}
isOpenOnDay(day):Boolean {
let _weekDay = day.getDay();
let _retour = false;
this.locations.forEach(loc => {
if (loc.id == this.selectedLocationId && loc.regularHours.weekDay == _weekDay) {
_retour = true;
}
});
this.locations.forEach(loc => {
if (loc.id == this.selectedLocationId && loc.specialDays.singleDate.getDay() == _weekDay) {
_retour = true;
}
});
return _retour;
}
getLocation():Number {
return this.selectedLocationId;
}
setLocation(id):void {
this.selectedLocationId = id;
}
getLocations():void {
this.api.getLocations().subscribe(
locations => {
this.locations = locations as BusinessLocation[];
this.setLocation(this.locations[0].id);
}
);
}
}
фрагмент из DB-services.component.ts
getLocations():Observable<BusinessLocation[]> {
return this.http.get(this.apiUrl + '/get_locations.php')
.map(response => response.json().data as BusinessLocation[]);
}
}
все работает отлично. Однако здесь есть проблема. Родительский компонент инициирует местоположения, но он также должен знать, какое местоположение выбрано прямо сейчас. Вот month.component.html
<span class="location-container" #location data-locations><span class="loading">Loading locations...</span></span>
<div *ngFor="let day of week.days" class="day" data-can-drop="day"
[class.today]="isToday(day)"
[class.in-other-month]="day.getMonth() != jsMonth"
[class.is-closed]="!isOpenAtLocation(day)">
<div class="day-marker"></div>
<span class="day-date">{{day | date:'d'}}</span>
<span *ngIf="checkMonth(day)" class="day-month">{{months[day.getMonth()]}}</span>
</div>
и фрагмент из month.component.ts является
@ViewChild('location') locationComponent:LocationComponent;
isOpenAtLocation(day):Boolean {
return this.locationComponent.isOpenOnDay(day);
}
ngOnInit(): void {
this.locationComponent.getLocations();
}
Я получаю ошибку довольно просто и вполне понятно:
Subscriber.ts:238 TypeError: Cannot read property 'forEach' of undefined
at LocationComponent.isOpenOnDay (location.component.ts:25)
at MonthComponent.isOpenAtLocation (month.component.ts:176)
И это как раз о вызове 1. Задача 2 еще не была рассмотрена.
Я просто не могу обернуть вокруг себя голову. > _ < Спасибо.