import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root', }) export class DataService { sharedData: any;
constructor() { } }
在组件中注入该服务,并在需要使用共享数据的组件中使用该服务:
import { Component } from '@angular/core'; import { DataService } from './data.service';
@Component({
selector: 'app-child',
template: {{ sharedData }}
,
})
export class ChildComponent {
sharedData: any;
constructor(private dataService: DataService) { this.sharedData = this.dataService.sharedData; }
changeData() { this.dataService.sharedData = 'New shared data'; } }
// 父组件 import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template:
,
})
export class ParentComponent {
data = 'Shared data';
handleOutput(data) { console.log(data); } }
// 子组件 import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: {{ inputData }}
,
})
export class ChildComponent {
@Input() inputData: any;
@Output() outputData =