J
J
jScheq2018-06-17 20:38:01
Angular
jScheq, 2018-06-17 20:38:01

How to access BehaviorSubject property from service?

Good day!
I have a TttService. It has a cells property. This is an array of objects. It only changes on the client. One component subscribes to its changes, the other - changes. Attention to the question: I want the makeAMove() method to change one of the properties of the desired object in the cells array, and at the same time, the component that is subscribed to the cells property should receive these changes. How can this be implemented?
PS if you do console.log(this.cells) in the makeAMove() method, it will be empty there. At the same time, the component that subscribes to cells through the initCells() method receives changes for the first time.
Service

import { Injectable } from '@angular/core';
import { TttServiceInteface } from '../interfaces/ttt-service-inteface';
import { CellInteface } from '../interfaces/cell-interface';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { asObservable } from './asObservable';

@Injectable()
export class TttService {
  public cells: BehaviorSubject<CellInteface[]> = new BehaviorSubject([]);

  constructor() { }

  initCells(fieldSize: number, fieldWidth: number): Observable<CellInteface[]> {
    const cells = [];

    for (let i = 0; i < fieldSize * fieldSize; i++) {
      cells.push({
        width: fieldWidth,
        height: fieldWidth,
        id: i
      });
    }
    this.cells.next(cells);

    return this.cells;
  }

  getCells() {
    return asObservable(this.cells);
  }

  makeAMove(id: number) {
    this.getCells()
      .subscribe((c: Array<CellInteface>) => {
        c.forEach(cell => {
          if (cell.id === id && !cell.id) {
            cell.value = 1;
          }
        });
        this.cells.next(c);
    });
}

Component
ngOnInit() {
    const border = (window.screen.availHeight - 150);
    this.fieldSize = 5;
    this.border = border + 100;

    this.tttService
      .initCells(this.fieldSize, border / this.fieldSize)
      .subscribe(cells => {
        console.log(cells);
        this.cells = cells;
      });
  }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question