在Angular 2中使用主题 [英] Using subjects in Angular 2

查看:72
本文介绍了在Angular 2中使用主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 main.service.ts

@Injectable()
export class AppService{
  private mainSource = new Subject<boolean>();
  main$ = this.mainSource.asObservable();
}

我的 app.component.ts

constructor(private appService: AppService){
  this.appService.main$.subscribe(
  working => {this.appService.main$(false);}
}

ngOnInit(){
    if (this.appService.main$){alert("Tio");}
}

我的app.component返回Cannot invoke an expression whose type lacks a call signature错误.而且无论是否实际满足条件,我的OnInit警报都会触发.在这种情况下,他们没有.

My app.component returns a Cannot invoke an expression whose type lacks a call signature error. And my OnInit alert fires regardless of whether or not the conditions have actually been met. In this case they have not.

订阅对我来说仍然很陌生,所以我不清楚我应该在这里做什么.我想将main$设置为false的初始值.并且当我的页面被加载时,我希望它仅在为真时才发出警报.

Subscriptions are still quite foreign to me, so I'm not clear on exactly what I should be doing here. I want to set my main$ to an initial value of false. And when my page is loaded, I would like it to alert only if it is true.

推荐答案

如果要更改Subject的值,最好为此创建一个单独的方法.在这种情况下,我添加了setWorking方法来更改Subject的布尔值.

If you want to change values on a Subject it is best to create a separate method for that. In this case I added a setWorking method to change the Subject's boolean value.

接下来,该组件订阅Subject(作为Observable返回),并侦听对该值的更改.

Next, the component subscribes to the Subject (which is returned as an Observable) and listens to changes to the value.

如果值更改,将调用subscribe块内的回调函数.

If the value changes, the callback function inside the subscribe block will be invoked.

服务

@Injectable()
export class AppService{
  private mainSource = new Subject<boolean>();
  main$ = this.mainSource.asObservable();

  setWorking(isWorking: boolean) {
    this.mainSource.next(isWorking);
  }
}

组件

private subscription: Subscription

constructor(private appService: AppService){ }

ngOnInit(){

  this.appService.setWorking(false);

  this.subscription = this.appService.main$.subscribe(isWorking => {
    if (isWorking) { alert("Tio"); }
  }
}

ngOnDestroy() {
    this.subscription.unsubscribe();
}

最后,您可以在订阅后添加this.appService.setWorking(true);函数调用,以显示警报.

At last, you could add a this.appService.setWorking(true); function call after the subscription, to have the alert show up.

PS:我添加了ngOnDestroy部分,因为在导航离开时订阅不会自动清除,因此会导致内存泄漏.您需要从rxjs/Subscription导入Subscription.

PS: I have added the ngOnDestroy part, since the subscription is not automatically cleared when navigating away and thus would create a memory leak. You need to import Subscription from rxjs/Subscription.

这篇关于在Angular 2中使用主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆