首页 > 其他 > 详细

angular 发布订阅

时间:2019-05-05 18:32:05      阅读:207      评论:0      收藏:0      [点我收藏+]

创建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);
    });
  }

}

 

angular 发布订阅

原文:https://www.cnblogs.com/stacey-zy/p/10815380.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!