angular2 - 服务价值不变

时间:2016-08-03 21:04:43

标签: javascript angularjs typescript angular routes

我有一条名为home的路线,它有三条子路线,文件,邮件和垃圾。在归属路由组件中,它有一个名为' myUser'的变量。我创建了一个服务,所以他们都可以共享myUser值,但由于某种原因,服务变量值不会改变。
服务

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 ; 
  }
} 

主页(父路线)

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(); 
  }
}

邮件(儿童路线)

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

1 个答案:

答案 0 :(得分:2)

您必须将HomeService注入到依赖关系数组或bootstrap提供程序中的MainComponent函数中,以便服务只实例化一次。

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

然后从两个组件元数据的HomeService数组中删除providers