Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

AngularrxjsOdservableobjectdidnupdateafterusesubscribe

I am trying to understand the rx.js library on angular. But my mind is blow up.

I have view component, to view my film gallery:

<div>
  <h3>The current search gets <span>{{_resultSearch.totalcountOfFilmsByKeyword}}</span> results</h3>
  <button class="btn btn-info btn-block" routerLink='/searchFilms'>Back to search</button>
</div>
<div class="d-flex flex-wrap container-fluid">
  <div *ngFor="let item of _resultSearch.currentFilmCollectionForView" class="col-xl-3 col-lg-4 col-md-6 col-sm-12">
    <div class="card">
      <img [src]="item.Poster">
      <div>
        <a [href]="item.imdbID" target="_blank" alt="No image">{{item.Title}} - {{item.Year}}</a>
      </div>
    </div>
  </div>
</div>
<div class="btn-group pull-xs-right">
  <button *ngFor="let page of PageNumbers" (click)="changePage(page)" class="btn btn-outline-primary" [class.active]="page == selectedPage">
    {{page}}
  </button>
</div>

this code use _resultSearch object to view the film collection items. The implementation of this object:

@Injectable({
  providedIn: 'root'
})
export class ResultModelIMDB implements ResultModelAbstract {

  totalcountOfFilmsByKeyword: number;  
  isValidAnswerFromServer: boolean; 
  currentFilmCollectionForView: FilmModelIMDB[];

}

This object is initialized in the component.ts code. And it need to update after initizlized the component and after click to buttons on the pager to get another films from server:

@Component({
  selector: 'app-view-films',
  templateUrl: './view-films.component.html',
  styleUrls: ['./view-films.component.css']
})
export class ViewFilmsComponent implements OnInit {

  ngOnInit() {
  }

  private pageSizer: Number;
  private selectedPage: number = 1;
  _resultSearch: ResultModelAbstract = new ResultModelIMDB();

  constructor(private _platform: PlatformAbstractService) {
    this.pageSizer = _platform.GetCountOfPages();
    this._platform.GetResultCollection("1").subscribe(
      collection => this._resultSearch = collection
    );
    console.log(this._resultSearch);
  }
  changePage(newPage: number) {
    this.selectedPage = newPage;
    console.log(this.selectedPage);
    this._platform.GetResultCollection(this.selectedPage.toString()).subscribe(

      collection => {
        console.log(collection);
        this._resultSearch = collection;
      }
    )
  }

  get PageNumbers(): number[] {
    return Array(this.pageSizer).fill(0).map((x, i) => i + 1);
  }
}

Finally this object is need to update from the plafrom server. The function to update this object implement here:

//   Получение коллекции фильмов для отображения
 // page - постраничный поиск внутри коллекции (если передается страница, то возможно извлечение коллекции из кеша)
  GetResultCollection (page?:string): Observable<ResultModelAbstract> {
    // проверка ведется ли поиск внутри коллекции
    let isNeedCasheSearch: boolean = page? true: false;
    if (isNeedCasheSearch)
    {
        // проверка есть ли текущая страница в кеше 
        if (this.HasFilmCollectionFromCache(page)) {
          console.log ("Extract collection from the cache");
          this._resultFilmModel.currentFilmCollectionForView = this.cacheCollectoin[Number(page) - 1];
        }
    }
    // делаем запрос к серверу
    else {
      this.fillQueryStringFromForm(page); 
      console.log ("Get collection from the server page: " +page);
      return this.httpserver.Get(this.queryString)
                    .map(item=> JSON.parse(item.Data) )
                    .map(dataitem => {
                      console.log (dataitem);
                      this._resultFilmModel.isValidAnswerFromServer = dataitem.Response;
                      this._resultFilmModel.currentFilmCollectionForView = dataitem.Search;
                      this._resultFilmModel.totalcountOfFilmsByKeyword = dataitem.totalResults;
                      console.log (this._resultFilmModel.isValidAnswerFromServer);
                      this.cacheCollectoin = new Array<FilmModelIMDB[]>();
                      this.cacheCollectoin[page] = dataitem.Search;
                      return this._resultFilmModel;
                    });
    }
    return Observable.of(this._resultFilmModel);
  }

The problem is that after I push the pager's button, the collection didn't update, moreover the last function didn't invoke. I know that my mistake is my poor knowledge for Observable's objects, please tell me what did I do wrong. Thanks.

Comments