简体   繁体   English

Angular2 - 订阅服务变量更改

[英]Angular2 - subscribe to Service variable changes

I have an authentication service that makes the authenticated variable equal to true or false. 我有一个身份验证服务,使经过身份验证的变量等于true或false。

checkAuthentication(){
  this._authService.getAuthentication()
    .subscribe(value => this.authenticated = value);
}

How do I execute a function when this.authenticated has changed value? this.authenticated更改值时,如何执行函数? ngOnChanges is not picking up the change. ngOnChanges没有发现变化。

To keep authenticated in service and share it between components you can use BehaviorSubject , it's value to check authentication in different places, and it's subscribe() method to react on change... 要在服务中进行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!")
  }
}

How do I execute a function when this.authenticated has changed value? this.authenticated更改值时,如何执行函数?

  this._authService.authenticated
   .subscribe((value: boolean) => console.log(value))

I think that you could leverage the get / set syntax of TypeScript to detect when your authenticated property of your service is updated: 我认为您可以利用TypeScript的get / set语法来检测服务的经过身份验证的属性何时更新:

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

When assigning a value, the "set authenticated" block is called. 分配值时,将调用“set authenticated”块。 For example with such code: 例如,使用这样的代码:

this.authenticated = true;

See this question for more details: 有关详细信息,请参阅此问题:

That said you could also leverage an EventEmitter property in the service. 也就是说你也可以利用服务中的EventEmitter属性。 When the authenticated property is updated, the corresponding event could be fired. 更新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);
    });
  }
}

See this link for more details: 有关详细信息,请参阅此链接:

It depends on who needs to handle the event. 这取决于谁需要处理该事件。 If it's the parent component, you can leverage output event bindings: 如果它是父组件,您可以利用输出事件绑定:

@Output authenticationChange: EventEmitter<Boolean> = new EventEmitter();
checkAuthentication(){
     this._authService.getAuthentication()
     .subscribe(value => 
           if(value != this.authenticated) {
               this.authenticated = value);
               this.authenticationChange.emit(value);
      });
 }

And in your parent component: 在您的父组件中:

 <directive (authenticationChange)="doSomething()">

I used a {{ showValue() }} in the component template, and in the .ts file I called the service's variable 我在组件模板中使用了{{ showValue() }} ,在.ts文件中我调用了服务的变量

showValue() {
   this.authenticated = this._authService.authenticated;
   return "dummy"
} 

Thanks to Angular2's GUI 2-way binding, it works. 感谢Angular2的GUI双向绑定,它可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM