简体   繁体   中英

angular2 - Service 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); 
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM