Skip to content

task#10 observables

bacn edited this page Sep 16, 2020 · 1 revision

Create an Observable

  1. Create the getObservableAuctions() method in the AuctionDataService class. We are using the rxjs library version 6. The method should use of(). The version 5 library was using Observable.of(). The imports have changed from version rxjs 5 to 6.
  2. Subscribe to it in the AuctionList component by adapting the constructor() method.

Result

Compile and start the application with

ng serve

Open project in browser


task9-result.png


Hints

AuctionDataService in file src/app/shared/auction-data.service.ts

Create a new method getObservableAuctions(). Please be awere the import for Observable.of is import {Observable} from 'rxjs/Rx';

import { Injectable } from '@angular/core';
import {Auction} from './auction';
import {AUCTION_DATA} from './auction-data';
import {Observable, of} from 'rxjs';

@Injectable()
export class AuctionDataService {

  private auctions: Auction[] = AUCTION_DATA;

  constructor() { }

  public getAuctions() {
    return this.auctions;
  }

  getObservableAuctions(): Observable<Auction[]> {
    return of(this.auctions);
  }
}

AuctionListComponent file src/app/auction-list/auction-list.component.ts

Implement the AuctionListComponent. Add auctionsObservable and auctionsSubscrition.

import {Component, EventEmitter, Input, OnDestroy, OnInit, Output} from '@angular/core';
import {Auction} from '../shared/auction';
import {AuctionDataService} from '../shared/auction-data.service';
import {Observable} from 'rxjs';
import {Subscription} from 'rxjs';

@Component({
  selector: 'app-auction-list',
  templateUrl: './auction-list.component.html',
  styleUrls: ['./auction-list.component.scss']
})
export class AuctionListComponent implements OnInit {
  @Input() headerTitle: string;
  @Output() titleClicked = new EventEmitter<string>();

  auctions: Auction[];
  auctionsObservable: Observable<Auction[]>;
  auctionSubscription: Subscription;

  constructor(private auctionDataService: AuctionDataService) {
    // this.auctions = auctionDataService.getAuctions();
    this.auctionsObservable = auctionDataService.getObservableAuctions();
    this.auctionSubscription = this.auctionsObservable.subscribe(data => this.auctions = data);
  }

  ngOnInit() {
  }

  onTitleClicked(event: MouseEvent): void {
    this.titleClicked.emit('Title clicked' + event.type);
  }

}

Clone this wiki locally