I am trying to update a variable declared in my component when the variable declared in my service changes. I am using Subject for this. However, nothing happens.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ShareDataService } from './share-data.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [ShareDataService],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
import { ShareDataService } from './share-data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
_subscription;
constructor(private shareDataService:ShareDataService)
{
//this.title=this.shareDataService.title;
this._subscription = shareDataService.titleChange.subscribe((value) => {
this.title = value;
//alert(this.title);
console.log("COmponent::::::::::::::"+this.title);
});
}
}
shareDataService.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class ShareDataService {
title:string="TITLE";
titleChange: Subject<string> = new Subject<string>();
constructor() {
setTimeout(
function()
{
this.title="BACDEF";
//console.log(this.title);
this.titleChange.next(this.title);
}
,1000);
}
}
It gives an error saying "Cannot read property 'next' of undefined" for the Subject defined in service. What would be the most appropriate way to implement this?
Use arrow function:
setTimeout(() => {
this.title="BACDEF";
this.titleChange.next(title);
}, 1000)
or bind:
setTimeout(function() {
this.title="BACDEF";
this.titleChange.next(title);
}.bind(this), 1000)
to get rid of that error. Otherwise this
in setTimeout's callback is a window object