创建一个服务并将此服务添加到共享父组件(或者如果没有,将其添加到应用程序组件的)提供者列表中。确保在需要使用服务的每个组件中导入服务。然后将服务注入到每个需要它的组件的构造函数中。
Plunkr 示例:https ://plnkr.co/l3BlNdjQfzPIIGPSXp9n?p=preview
// >>>home.ts
import { Component } from "@angular/core";
import { Component1 } from "./component1.ts";
import { Component2 } from "./component2.ts";
import { YearService } from "./year.service.ts"
@Component({
templateUrl:"home.html",
directives: [Component1, Component2],
providers: [YearService]
})
export class HomePage {
constructor() { }
}
// >>>home.html
<ion-header>
<ion-navbar primary>
<ion-title>
Ionic 2
</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<comp-one></comp-one>
<comp-two></comp-two>
</ion-content>
// >>>component1.ts
import { Component } from "@angular/core";
import { YearService } from "./year.service.ts";
@Component({
templateUrl: "./component1.html",
selector: "comp-one"
})
export class Component1 {
constructor(yearSvc: YearService) {
this.year = yearSvc.getYear();
}
}
// >>>compnent1.html
<p> Year from component 1 using a shared service: <strong>{{year}}</strong></p>
// >>>component2.ts
import { Component } from "@angular/core";
import { YearService } from "./year.service.ts";
@Component({
templateUrl: "./component2.html",
selector: "comp-two",
})
export class Component2 {
constructor(yrSvc: YearService) {
this.year = yrSvc.getYear();
}
}
// >>> component2.html
<p> Year from component 2 using a shared service: <strong>{{year}}</strong></p>
// >>> year.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class YearService {
getYear() {
return new Date().getFullYear();
}
}