Angular、订阅和变量更新的问题
创始人
2024-11-01 16:30:26
0

在Angular中使用RxJS中的订阅机制来实时更新变量值。

首先,在组件中声明RxJS的Observable类型变量,并使用ngOnInit方法来订阅它:

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {

  myObservable$: Observable;

  constructor() { }

  ngOnInit() {
    this.myObservable$ = new Observable(observer => {
      setInterval(() => {
        observer.next(new Date().toString()); // 发出新值
      }, 1000);
    });
  }

}

然后,在模板中使用async管道来实时显示Observable中发出的新值:

{{ myObservable$ | async }}

这样,每秒钟组件的模板就会更新一次,显示最新的日期值。

注意:在组件销毁时,应该取消订阅以避免内存泄漏:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable, Subscription } from 'rxjs';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit, OnDestroy {

  myObservable$: Observable;
  subscription: Subscription;

  constructor() { }

  ngOnInit() {
    this.myObservable$ = new Observable(observer => {
      this.subscription = setInterval(() => {
        observer.next(new Date().toString()); // 发出新值
      }, 1000);
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe(); // 取消订阅
  }

}

相关内容

热门资讯

透视教你"wepok... 透视教你"wepoker有用吗"切实真的有辅助技巧(哔哩哔哩)wepoker有用吗破解侠是真的助透视...
透视必备"wpk刷入... 透视必备"wpk刷入池率脚本"真是真的是有辅助挂(哔哩哔哩)1)wpk刷入池率脚本辅助插件:进一步探...
透视透视"wepok... 透视透视"wepoker黑侠辅助器正版下载"都是真的有辅助教程(哔哩哔哩)wepoker黑侠辅助器正...
透视关于"wepok... 透视关于"wepoker私人局外卦"一贯是有辅助技巧(哔哩哔哩)1、wepoker私人局外卦辅助软件...
透视了解"wepok... 透视了解"wepoker透视破解版"好像真的是有辅助软件(哔哩哔哩)1、该软件可以轻松地帮助玩家将w...
透视分享"wepok... 透视分享"wepoker钻石怎么看底牌"都是存在有辅助器(哔哩哔哩)一、wepoker钻石怎么看底牌...
透视分享"wepok... 透视分享"wepoker可以透视码"都是有辅助软件(哔哩哔哩)wepoker可以透视码透视方法中分为...
透视解谜"steam... 透视解谜"steampokermaster辅助"原来有辅助方法(哔哩哔哩)进入游戏-大厅左侧-新手福...
透视普及"wepok... 透视普及"wepoker买脚本靠谱吗"一直有辅助神器(哔哩哔哩)1、透视普及"wepoker买脚本靠...
透视教你"aapok... 透视教你"aapoker万能辅助器"总是有辅助神器(哔哩哔哩)1、起透看视 aapoker万能辅助器...