角度 2 服务中的变化检测

Angular 2 Change detection in service

本文关键字:变化检测 服务 角度      更新时间:2023-09-26

我正在查看Angular 2测试版,并且正在努力解决更改检测的工作原理。我做了一个简单的 plunkr 示例,显示了我遇到的一个问题。

//our root app component
import {Component, Injectable} from 'angular2/core'
@Injectable()
export class AuthService {
  public state: boolean = true;
  
  change() {
    this.state = false;
    console.log(this.state);
  }
}
@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <p>{{state}}</p>
      <button (click)="doLogout()" class="btn btn-success">logout</button>
      <button (click)="changeName()" class="btn btn-success">change name</button>
    </div>
  `,
  directives: [],
  providers: [AuthService],
})
export class App {
  constructor(_auth: AuthService) {
    this.name = 'Angular2';
    this._auth = _auth;
    this.state = _auth.state;
  }
  
  doLogout() {
    this._auth.change();
  }
  
  changeName() {
    this.name = "something else";
  }
}

当您按下注销按钮时,我正在更新身份验证服务中的状态值。我希望视图也会更新其显示的值,但是当它应该更新为 false 时,它保持为真。但是,打印的控制台值是正确的。

https://plnkr.co/edit/CJBjRvyO9aSV0SSHm66R?p=preview

有人可以解释为什么它不起作用,以及我如何解决它。

您只分配一次this.state - 在创建App组件时在构造函数中。以后的更改不会反映。

您可能希望改为绑定到<p>{{_auth.state}}</p>或订阅服务中的EventEmitter,并在每次在服务中更新值时更新state。有关示例,请参阅 Plunker。

这不是一个角度 2 问题。Angular 检测引用中的更改,这不是引用:

this.state = _auth.state;

更改如下:

{{_auth.state}}