-
Notifications
You must be signed in to change notification settings - Fork 0
task#11 component life cycle
bacn edited this page Sep 16, 2020
·
1 revision
- Refactor components: they should load data in
ngOnInit() - Import
OnInit - Implement
ngOnInit() - Keep in mind: unsubscribe from the (longliving) observable when the component gets destroyed. Use for it
ngOnDestroy()
Compile and start the application with
ng serve
Open project in browser
- Open your browser with the address http://localhost:4200/
- In the browser window shall appear:

Angular Guide, Lifecycle Hooks https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html
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();
}
}