Angular 2 - 将会话变量链接到组件变量

时间:2016-10-20 16:12:29

标签: angular

我有两个导入服务的不同组件。 这项服务有一个属性。

我在组件中使用此属性。 我希望在更新服务属性时更新组件对该值的引用。

服务

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

@Injectable()
export class SessionService {

    private loggedIn: boolean = false;

    isLoggedIn():boolean{
        return this.loggedIn;
    }


    setLoggedIn(isLoggedIn: boolean){
        this.loggedIn = isLoggedIn;
    }
}

组件属性:

 isSignedIn: boolean = this.session.isLoggedIn();

组件的区域html:

    <div *ngIf="isSignedIn">
        <sd-header-signed-in></sd-header-signed-in>
    </div>
    <div *ngIf!="isSignedIn">
        <sd-header-signed-out></sd-header-signed-out>
    </div>

当我通过按钮更改会话值时,它不会更改组件中的值。

由于

1 个答案:

答案 0 :(得分:3)

你需要这样做:

<div *ngIf="session.isLoggedIn()">
   <sd-header-signed-in></sd-header-signed-in>
</div>
<button (click)="session.setLoggedIn(true)">Set session</button>

因为 isSignedIn 变量只评估一次

以下是完整代码:

import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

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

@Injectable()
export class SessionService {

    private loggedIn: boolean = false;

    isLoggedIn():boolean{
        return this.loggedIn;
    }

    setLoggedIn(isLoggedIn: boolean){
        this.loggedIn = isLoggedIn;
    }
}

@Component({
  selector: 'first-component',
  template: `
    <div>
      <h2>FirstComponent</h2>
    </div>
  `,
})
export class FirstComponent {
  constructor(public sessionService: SessionService) {

  }
}


@Component({
  selector: 'second-component',
  template: `
    <div>
      <h2>SecondComponent</h2>
      <ng-content></ng-content>
    </div>
  `,
})
export class SecondComponent {
   constructor(public sessionService: SessionService) {

  }
}


@Component({
  selector: 'my-app',
  template: `
    <div>
      <button (click)="sessionService.setLoggedIn(true)">Set session</button>
      <first-component *ngIf="sessionService.isLoggedIn()"></first-component>
      <second-component *ngIf="sessionService.isLoggedIn()">
        <button (click)="sessionService.setLoggedIn(false)">Remove session</button>
      </second-component>
    </div>
  `,
})
export class App {
  constructor(public sessionService: SessionService) {

  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, SecondComponent,FirstComponent  ],
  providers: [SessionService],
  bootstrap: [ App ]
})
export class AppModule {}

工作人员: Plunker