簡體   English   中英

使用Angular 2中的主題

[英]Using subjects in 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錯誤Cannot invoke an expression whose type lacks a call signature 無論條件是否真正得到滿足,我的OnInit警報都會觸發。 在這種情況下,他們沒有。

訂閱對我來說仍然很陌生,所以我不清楚我應該在這做什么。 我想將我的main$設置為初始值false。 當我的頁面加載時,我希望它只有在它是真的時才會發出警報。

如果要更改主題上的值,最好為其創建單獨的方法。 在這種情況下,我添加了一個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);
  }
}

零件

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); 訂閱后的函數調用,以顯示警報。

PS:我添加了ngOnDestroy部分,因為導航時不會自動清除訂閱,因此會造成內存泄漏。 您需要導入Subscriptionrxjs/Subscription

問題是,您在構造函數中訂閱。 所以你不知道結果何時到來,因為它是異步的。 與此同時,構造函數立即完成,並調用OnInit。

我不知道你的服務是怎樣的,但如果你也訂閱OnInit方法中的事件,那將是最好的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM