美文网首页
原生ng广播 Subject 观察者模式

原生ng广播 Subject 观察者模式

作者: 蒋小花_4b6c | 来源:发表于2022-01-20 14:36 被阅读0次

    service

    import { Subject } from 'rxjs';

    import { Observable } from 'rxjs';

    export class MessageService {

        private subject =newSubject();

        send(message: any) {

            this.subject.next(message);

        }

        get(): Observable {

            returnthis.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 =newSubject();

      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);

        });

      }

    }

    相关文章

      网友评论

          本文标题:原生ng广播 Subject 观察者模式

          本文链接:https://www.haomeiwen.com/subject/lkpjhrtx.html