服务的作用:服务Service就是提供给APP数据模型的全局变量,而服务存在的目的就是对各个controller之间的交互提供了一个途径。在angular变量中由于controller作用域的问题,平级作用于之间无法相互沟通,而在开始发过程中controller之间的沟通无法避免,为了解决这个问题,angular框架提出了service功能。使用service需要注入实现,注入则相当于声明。
parent.html:
<h2>{{num}}</h2>
<page-child></page-child>
parent.ts:
import { Component }from'@angular/core';
import{myService}from'../child/myService';
export class ParentPage {
num:number=0;
constructor(service:myService) {
service.num = this.num + 10
}
}
child.html:
<h2>{{service.num}}</h2>
child.ts:
import { Component}from'@angular/core';
import{myService}from"../child/myService"
export class ChildPage {
constructor(public service:myService){
}
}
myService.ts:(ps:记得在app.module.ts 加上providers: [KmyService])
import{Injectable }from'@angular/core';
@Injectable()
export class KmyService {
num:number =0;
}