2016-08-03 44 views
0

我有一條路線稱爲家,它有三個子路線,文件,郵件和垃圾。在home路由組件中,它有一個名爲'myUser'的變量。我創建了一個服務,以便它們都可以共享myUser值,但出於某種原因,服務變量值不會更改。
服務angular2 - 服務價值不變

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

回答

2

你必須注入HomeService成依賴陣列或MainComponent提供商要麼bootstrap功能這樣服務將只實例化一次。

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

然後從providers陣列兩種組分的元數據中刪除HomeService

+0

我試過這種方法,問題依然存在。 – John

+0

@John你必須從'提供者'數組中從'component'中移除'HomeService' .. –

+0

是的,當我刪除提供者時,我看到了你的編輯工作。這是爲什麼? – John