Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alx8437/9b9c315caee90487a723347924f70084 to your computer and use it in GitHub Desktop.
Save alx8437/9b9c315caee90487a723347924f70084 to your computer and use it in GitHub Desktop.
// component for output data
import {Component, OnInit} from '@angular/core';
import {PictureDate, PictureService} from '../../services/picture.service';
import {StateService} from '../../services/state.service';
@Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.scss']
})
export class HomePageComponent implements OnInit {
picture: PictureDate[] = [];
checkedItemBay: PictureDate[] = [];
constructor(private pictureService: PictureService,
private stateService: StateService) { // Импорт сервиса где реализован observable
}
ngOnInit(): void {
this.pictureService.getPhotos()
.subscribe((picture: PictureDate[]) => {
this.picture = picture;
console.log(picture);
});
}
log(): void {
this.picture.map(p => {
console.log(p);
});
}
changeStatus(pictureItem): void {
this.checkedItemBay.push(pictureItem);
this.checkedItemBay = this.checkedItemBay.filter(item => {
return item.isChecked === true;
});
// Передаем в метод сервиса нужный объект
this.stateService.setPictureItems(this.checkedItemBay);
}
}
// Service for transfer data
import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {PictureDate} from './picture.service';
@Injectable({
providedIn: 'root'
})
export class StateService {
// Создаем переменную "издатель для трансляции входящих данных"
picturesState: BehaviorSubject<PictureDate[]> = new BehaviorSubject([]);
constructor() {
}
// Метод передачи данных в "транслятор"
setPictureItems(value): void {
this.picturesState.next(value);
}
}
// Component for input data
import {Component, OnInit, OnDestroy} from '@angular/core';
import {StateService} from '../../services/state.service';
import {Subscription} from 'rxjs';
import {PictureDate} from '../../services/picture.service';
@Component({
selector: 'app-shopping-cart',
templateUrl: './shopping-cart.component.html',
styleUrls: ['./shopping-cart.component.scss']
})
export class ShoppingCartComponent implements OnInit, OnDestroy {
shopItemBay: PictureDate[] = [];
pictures$: Subscription;
constructor(private stateService: StateService) {
}
ngOnInit(): void {
// 1) Импортируем сервис, который транслирует данные
// 2) Подписываемся к "трансляции" данных из сервиса и назначаем их переменной
this.pictures$ = this.stateService.picturesState
.subscribe(data => {
console.log(data);
this.getItem(data);
});
}
ngOnDestroy(): void {
this.pictures$.unsubscribe();
}
getItem(data): void {
this.shopItemBay.push(data);
}
log(): void {
console.log(this.shopItemBay);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment