zoukankan      html  css  js  c++  java
  • angular service 进行组件通信

    MessageService 代码如下

    import { Injectable } from '@angular/core';
    import { Subject } from 'rxjs';
    @Injectable({
      providedIn: 'root'
    })
    export class MessageService {
      private messageSource = new Subject<string>();
      message$ = this.messageSource.asObservable();
      messageAction(name: string) {
        this.messageSource.next(name);
      }
    }
    

    发送消息的组件 代码如下

    ts

    import { Component} from '@angular/core';
    import { MessageService } from '../service/message.service';
    @Component({
      selector: 'app-send',
      templateUrl: './send.component.html',
      styleUrls: ['./send.component.css']
    })
    export class SendComponent {
      constructor(private messageService: MessageService) { }
      sendMessage(action: string) {
        this.messageService.messageAction(action);
      }
    

    html

    <input #action>
    <button (click)="sendMessage(action.value)">action</button>
    

    接收消息的组件

    ts

    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { MessageService } from './service/message.service';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit, OnDestroy {
      action: string;
      sub: Subscription;
      ngOnInit(): void {
        this.messageService.message$.subscribe(action => this.action = action);
      }
      ngOnDestroy(): void {
        this.sub.unsubscribe(); //不要忘记取消订阅
      }
      constructor(private messageService: MessageService) {
      }
    
  • 相关阅读:
    CSS hack——不同浏览器的CSS应对法
    IE6对CSS支持Bug收集
    jQuery
    jQuery学习备忘
    MSSQLSERVER之发布-分发-订阅
    利用Resgen.exe 批量生成resources文件
    多语言处理
    c# winform 打包部署 自定义界面 或设置开机启动
    C#修改文件夹权限
    VS2008 Windows Form项目安装包生成详解
  • 原文地址:https://www.cnblogs.com/Godfunc/p/9848713.html
Copyright © 2011-2022 走看看