簡體   English   中英

在TypeScript回調方法中聲明類屬性

[英]Declare class properties inside typescript callback method

我有一種方法可以從pub子消息服務訂閱事件。 在回調中,我想定義一個類屬性。 當我嘗試分配屬性值時,它以未定義的形式返回。 我知道對“ this”的引用已從類更改為方法,但我需要它具有訪問類的“ this”屬性的權限。 如何在回調方法中將值分配給類屬性“ this.icon”?

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription'
import { Events } from '../shared/messages/events';
import { MessageService } from '../shared/messages/message.service';

export class Component implements OnInit, OnDestroy {

  public icon: string;
  private subscription: Subscription;

  constructor() { this.btnClickSubscribe();}

  private btnClickSubscribe(): void {

     this.subscription = this.messageService
        .subscribe(Events.btnClick, (payload) => {

        this.icon = 'fa-trash-o'; 

        console.log(this.icon) //logs the correct value, 'fa-trash-o' 
        //but it's only available inside this context. I need it in the 
        //class context     
  });
 }

由於這是一個異步事件, this.icon無論您執行什么操作, this.icon最初在回調之外都是未定義的。 選中此復選框以獲取更多信息: 如何從angular2中的Observable / http / async調用返回響應?

您提到過要通過@Input()icon傳遞給子@Input()然后利用子ngOnChanges中的ngOnChanges來捕獲對icon發生的更改。 ngOnChanges您可以創建一個條件,該條件將值設置為icon 執行您想執行的任何邏輯,因此在您的孩子中這樣的操作:

@Input() icon;

ngOnChanges() {
  if(this.icon) {
    console.log('icon is set, now do something with it!')
  }
}

並且,如果您對視圖有疑問,可以使用一些可行的解決方案,例如使用安全導航運算符,在此處獲取更多信息: 無法讀取未定義的屬性“ totalPrice”

這是一個

演示

希望這可以幫助! :)

暫無
暫無

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

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