Use lifecycle hooks to unsubscribe

This commit is contained in:
William Welling
2016-12-01 13:16:39 -06:00
parent 1a8aabc996
commit 8268845cf0

View File

@@ -1,4 +1,4 @@
import { Component, ChangeDetectionStrategy, OnInit, ViewEncapsulation } from '@angular/core';
import { Component, ChangeDetectionStrategy, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { TranslateService } from 'ng2-translate';
@@ -9,7 +9,7 @@ import { TranslateService } from 'ng2-translate';
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
export class AppComponent implements OnDestroy, OnInit {
example: string;
@@ -18,6 +18,8 @@ export class AppComponent implements OnInit {
recipient: 'World'
}
private registerSubscription: any;
constructor(public translate: TranslateService) {
// this language will be used as a fallback when a translation isn't found in the current language
translate.setDefaultLang('en');
@@ -26,9 +28,15 @@ export class AppComponent implements OnInit {
}
ngOnInit() {
this.translate.get('example.with.data', { greeting: 'Hello', recipient: 'DSpace' }).subscribe((res: string) => {
this.example = res;
this.registerSubscription = this.translate.get('example.with.data', { greeting: 'Hello', recipient: 'DSpace' }).subscribe((translation: string) => {
this.example = translation;
});
}
ngOnDestroy() {
if (this.registerSubscription) {
this.registerSubscription.unsubscribe();
}
}
}