查看: 8|回覆: 0

angular 发布订阅

[複製鏈接]

4

主題

0

回帖

0

積分

热心网友

金币
0
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2011-11-14
發表於 2019-5-5 18:15:00 | 顯示全部樓層 |閲讀模式

创建service

import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/observable';

export class MessageService {
    private subject = new Subject<any>();

    send(message: any) {
        this.subject.next(message);
    }

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

组件1 发布

import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { MessageService } from '../../service/message.service';

@Component({
  selector: 'app-video-demo-home',
  templateUrl: './video-demo-home.component.html',
  styleUrls: ['./video-demo-home.component.sass']
})
export class VideoDemoHomeComponent implements OnInit {

  private _clickPoint: Subject<any> = new Subject<any>();
  public name = 'www';
  constructor(public srv: MessageService) { }


  ngOnInit() {
  }

  clickBtn() {
    this.srv.send(this.name);
  }

}

组件2 订阅

import { Component, OnInit } from '@angular/core';
import { MessageService } from '../../service/message.service';

@Component({
  selector: 'app-subscribe-home',
  templateUrl: './subscribe-home.component.html',
  styleUrls: ['./subscribe-home.component.sass']
})
export class SubscribeHomeComponent implements OnInit {

  constructor(public srv: MessageService) { }
  public message = '';
  ngOnInit() {

    this.srv.get().subscribe((result) => {
      console.log('111111111111111111');
      this.message = result;
      console.log(this.message);
    });
  }

}

 



来源:https://www.cnblogs.com/stacey-zy/p/10815380.html
回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部