angular项目中实现rxjs订阅

getMessage.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonService } from '../services/common.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit, OnDestroy {
  list: any;
  title: string;
  message = 'scotter';
  test: string;
  subscription: Subscription;

  constructor(
    private commonService: CommonService
  ) {
    this.list = commonService.dateList;
    this.title = commonService.content;
    this.subscription = this.commonService.getMessage().subscribe(message => {
      console.log(message);
      if (message) {
        this.message = message.data;
      } else {
        this.message = null;
      }
    });
  }

  ngOnInit() {

  }

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

  getCommonContent() {
    console.log(this.message);
  }

}

sendMessage.ts
import { Component, OnInit } from '@angular/core';
import { CommonService } from '../services/common.service';

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

  constructor(
    private commonService: CommonService
  ) { }

  ngOnInit() {
  }

  sendMessage(): void {
    // send message to subscribers via observable subject
    this.commonService.sendMessage('我是改变后的内容');
  }

  clearMessage(): void {
      // clear message
      this.commonService.clearMessage();
  }


}

commonService.ts
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CommonService {

  public content = 'haha';
  public dateList: any = [
    {
      name: '张旭超',
      age: 20,
      address: '北京市朝阳区'
    }
  ];
  test1 = '我是test数据';

  private subject = new Subject<any>();

  sendMessage(message: Object) {
    this.subject.next({ data: message });
  }

  clearMessage() {
    this.subject.next();
  }

  getMessage(): Observable<any> {
    return this.subject.asObservable();
  }

  constructor() { }

  addDateFun(data: any) {
    this.dateList.push(data);
  }

  changeContent(str: any) {
    this.content = str;
    console.log(this.content);
  }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值