John John - 4 months ago 23
TypeScript Question

angular2 - Serivce value not changing

I have a route called home and it has three child routes, documents, mail and trash. In the home route component it has a variable called 'myUser'. I created a service so they can all share the myUser value, but for some reason the service variable value doesn’t change.


Service

import { Injectable } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';

@Injectable()
export class HomeService {
// Mock user, for testing
myUser = {name:"John", loggedIn:true};

setUser(name:string){
this.myUser.name = name ;
}

isLogged():boolean {
if(this.myUser.loggedIn == true){
return true ;
}
return false ;
}
}


Home (parent route)

import { Component } from '@angular/core';
import { Router, ROUTER_DIRECTIVES } from '@angular/router';
import { CORE_DIRECTIVES, FORM_DIRECTIVES } from '@angular/common';
import { Http, Headers } from '@angular/http';
import { contentHeaders } from '../common/headers';

import { HomeService } from '../../home.service';


const template = require('./home.component.html');
const styles = require('./home.component.css');

@Component({
selector: 'home',
directives: [ CORE_DIRECTIVES, FORM_DIRECTIVES ],
template: template,
styles: [ styles ],
providers: [HomeService]
})

export class HomeComponent {
constructor(public router: Router, private homeService: HomeService) {

}
myUser = this.homeService.myUser ;

setUser(name:string){
this.homeService.setUser(name);
}

// Is logged in
isLogged():boolean {
return this.homeService.isLogged();
}
}


Mail (child route)

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { CORE_DIRECTIVES, FORM_DIRECTIVES } from '@angular/common';
import { HomeService } from '../../home.service';


const template = require('./mail.component.html');
const styles = require('./mail.component.css');

@Component({
selector: 'mail',
directives: [ CORE_DIRECTIVES, FORM_DIRECTIVES ],
template: template,
styles: [ styles ],
providers: [HomeService]
})

export class MailComponent {
constructor(public router: Router, private homeService: HomeService) {

}

myUser = this.homeService.myUser ;

setUser(name:string){
this.homeService.setUser(name);
}
}

Answer

You have to inject HomeService into either bootstrap function in Dependency array or MainComponent providers so that service will instantiate only once.

bootstrap(MainComponent, [HomeService, ....other dependency...])

And then remove HomeService from providers array of both the components metadata.

Comments