angular 發布訂閱


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

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM