【Angular】Angular中的服务service与组件间通信

1. 为什么需要使用服务?

Angular的service是一个简单的TypeScript类,它封装了一些用于完成应用程序中特定任务的方法,例如从服务器获取数据或者向服务器发送数据。

Angular中所有组件都可以调用服务中的方法,但是服务中无法调用组件的方法。组件不可直接调用其他组件的方法(组件之间可以父子组件传值),但是服务之间可以相互调用方法。

Angular Service 具有以下的作用:

  1. 用来将应用程序中的业务逻辑组件中的渲染逻辑分离
  2. 用来在Angular应用中的多个组件之间共享数据
  3. 让程序易于测试和调试
  4. 用于编写可重用的代码。

2. 创建服务

  1. 创建服务命令ng g s 服务位置/名称 (缩写g:generate,s:service)
  2. 要想在其他组件中使用服务,需要在根模块中app.module.ts中引入并配置服务。import {服务名} from '服务地址'; 并在provider中配置服务。(declaration是声明组件,imports是引入模块,provider是声明服务)
  3. 然后在服务service.ts中就可以写公共方法了
  4. 然后在其他组件中使用的时候,再在头部引入此服务import {服务名} from ‘服务地址’
  5. 此时注意,需要在构造函数的小括号中声明,如constructor(public 名:服务名){} 然后可以使用this.storage使用服务的实例。

3. service 进行组件间通信

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

3.2 发送消息的组件 代码如下
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>

3.3 接收消息的组件
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.sub = this.messageService.message$.subscribe(action => this.action = action);
  }
  ngOnDestroy(): void {
    this.sub.unsubscribe(); //不要忘记取消订阅
  }
  constructor(private messageService: MessageService) {
  }

注意收不到消息可能是

https://segmentfault.com/q/1010000025141404
https://segmentfault.com/a/1190000018078216?utm_source=sf-similar-article
https://segmentfault.com/a/1190000011425280

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卸载引擎

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值