码迷,mamicode.com
首页 > 其他好文 > 详细

angular service 进行组件通信

时间:2018-10-25 12:11:20      阅读:305      评论:0      收藏:0      [点我收藏+]

标签:select   订阅   export   new   click   rom   接收   script   dcom   

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) {
  }

angular service 进行组件通信

标签:select   订阅   export   new   click   rom   接收   script   dcom   

原文地址:https://www.cnblogs.com/Godfunc/p/9848713.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!