Angular2 - 订阅服务变量更改

Cli*_*ick 18 typescript angular

我有一个身份验证服务,使经过身份验证的变量等于true或false.

checkAuthentication(){
  this._authService.getAuthentication()
    .subscribe(value => this.authenticated = value);
}
Run Code Online (Sandbox Code Playgroud)

如何this.authenticated更改值时如何执行函数?ngOnChanges没有发现变化.

Sas*_*sxa 27

为了保持authenticated服务并在你可以使用的组件之间共享它 BehaviorSubject,它是value在不同的地方检查身份验证,它是subscribe()对变化作出反应的方法......

class AuthService {
  public authenticated = new BehaviorSubject(null);
  getAuthentication() {
    this._http.get('/authenticate')
      .map(response => response.json())
      .map(json => Boolean(json)) // or whatever check you need...
      .subscribe((value: boolean) => this.authenticated.next(value))
  }
}

class Component {
  constuctor(private _authService: AuthService) {
    // Only check once even if component is 
    // destroyed and constructed again
    if (this._authService.authenticated.value === null)
      this._authService.getAuthentication();
  }

  onSubmit(){
    if (!this._authService.authenticated.value)
      throw new Error("You are authenticated!")
  }
}
Run Code Online (Sandbox Code Playgroud)

如何this.authenticated更改值时如何执行函数?

  this._authService.authenticated
   .subscribe((value: boolean) => console.log(value))
Run Code Online (Sandbox Code Playgroud)


Thi*_*ier 10

我认为您可以利用TypeScript的get/set语法来检测服务的经过身份验证的属性何时更新:

  private _authenticated:Boolean = false;
  get authenticated():Boolean {
        return this._authenticated ;
  }
  set authenticated ( authenticated Boolean) {
    // Plugin some processing here
      this._ authenticated = authenticated;
  }
Run Code Online (Sandbox Code Playgroud)

分配值时,将调用"set authenticated"块.例如,使用这样的代码:

this.authenticated = true;
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此问题:

也就是说你也可以利用服务中的EventEmitter属性.更新authenticated属性后,可以触发相应的事件.

export class AuthService {
  authenticatedChange: Subject<boolean> = new Subject();

  constructor() {}

  emit(authenticated) {
    this.authenticatedChange.next(authenticated);
  }

  subscribe(component, callback) {
    // set 'this' to component when callback is called
    return this.authenticatedChange.subscribe(data => {
      callback(component, data);
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此链接: