使用Angular 2中的主题

abr*_*din 3 rxjs angular

我的main.service.ts

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

我的app.component.ts

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

ngOnInit(){
    if (this.appService.main$){alert("Tio");}
}
Run Code Online (Sandbox Code Playgroud)

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

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

Ale*_*ski 6

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

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

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

服务

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

  setWorking(isWorking: boolean) {
    this.mainSource.next(isWorking);
  }
}
Run Code Online (Sandbox Code Playgroud)

零件

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();
}
Run Code Online (Sandbox Code Playgroud)

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

PS:我添加了ngOnDestroy部件,因为导航时不会自动清除订阅,因此会造成内存泄漏.你需要导入Subscriptionrxjs/Subscription.