Angular中的服务service
1. 为什么需要使用服务?
Angular的service是一个简单的TypeScript类,它封装了一些用于完成应用程序中特定任务的方法,例如从服务器获取数据或者向服务器发送数据。
Angular中所有组件都可以调用服务中的方法,但是服务中无法调用组件的方法。组件不可直接调用其他组件的方法(组件之间可以父子组件传值),但是服务之间可以相互调用方法。
Angular Service 具有以下的作用:
- 用来将应用程序中的业务逻辑组件中的渲染逻辑分离
- 用来在Angular应用中的多个组件之间共享数据
- 让程序易于测试和调试
- 用于编写可重用的代码。
2. 创建服务
- 创建服务命令
ng g s 服务位置/名称
(缩写g:generate,s:service) - 要想在其他组件中使用服务,需要在根模块中app.module.ts中引入并配置服务。
import {服务名} from '服务地址';
并在provider中配置服务。(declaration是声明组件,imports是引入模块,provider是声明服务) - 然后在服务service.ts中就可以写公共方法了
- 然后在其他组件中使用的时候,再在头部引入此服务
import {服务名} from ‘服务地址’
- 此时注意,需要在构造函数的小括号中声明,如
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