Skip to content

task#11 component life cycle

bacn edited this page Sep 16, 2020 · 1 revision

Component LifeCycle Basic

  1. Refactor components: they should load data in ngOnInit()
  2. Import OnInit
  3. Implement ngOnInit()
  4. Keep in mind: unsubscribe from the (longliving) observable when the component gets destroyed. Use for it ngOnDestroy()

Result

Compile and start the application with

ng serve

Open project in browser


task9-result.png


Hints

Angular Guide, Lifecycle Hooks https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

auction-list.component.ts

Move the subscribe of the auction data observable from the constructor to ngOnInit(). Implement the interface ngOnDestroy(). Don't for get to Import onDestroy and adjust the class declaration to: export class AuctionListComponent implements OnInit, OnDestroy.

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, OnDestroy {
  @Input() headerTitle: string;
  @Output() titleClicked = new EventEmitter<string>();

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

  constructor(private auctionDataService: AuctionDataService) {
    // this.auctions = auctionDataService.getAuctions();
  }

  ngOnInit() {
    this.auctionsObservable = this.auctionDataService.getObservableAuctions();
    this.auctionSubscription = this.auctionsObservable.subscribe(data => this.auctions = data);
  }

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

  ngOnDestroy() {
    this.auctionSubscription.unsubscribe();
  }


}

Clone this wiki locally