,可以通过以下步骤实现:
import { Injectable } from '@angular/core';
@Injectable()
export class SharedService {
sharedData: any;
constructor() { }
}
import { NgModule } from '@angular/core';
import { SharedService } from './shared.service';
@NgModule({
providers: [SharedService],
// ...
})
export class AppModule { }
import { Component } from '@angular/core';
import { SharedService } from './shared.service';
@Component({
selector: 'app-child-component',
template: `
<div>{{ sharedData }}</div>
`
})
export class ChildComponent {
sharedData: any;
constructor(private sharedService: SharedService) {
this.sharedData = sharedService.sharedData;
}
}
import { Injectable } from '@angular/core';
@Injectable()
export class SharedService {
sharedData: any;
constructor() { }
setSharedData(data: any) {
this.sharedData = data;
}
getSharedData() {
return this.sharedData;
}
}
import { Component } from '@angular/core';
import { SharedService } from './shared.service';
@Component({
selector: 'app-parent-component',
template: `
<button (click)="setSharedData()">Set Shared Data</button>
<app-child-component></app-child-component>
`
})
export class ParentComponent {
constructor(private sharedService: SharedService) { }
setSharedData() {
this.sharedService.setSharedData('Shared data from parent component');
}
}
通过以上步骤,不共享同一父组件的子组件之间就可以共享Angular 2服务了。子组件可以通过注入该服务并访问其中的共享数据或功能。请注意,这种方式只适用于不共享同一父组件的子组件之间的共享,如果子组件共享同一父组件,可以直接通过父组件进行数据传递。
领取专属 10元无门槛券
手把手带您无忧上云