
Angular 4 中使用共享服务实现多组件间的数据通信示例
5星
- 浏览量: 0
- 大小:None
- 文件类型:None
简介:
本文将介绍如何在Angular 4框架中利用共享服务实现不同组件之间的数据交互与通信,提供一个实用示例。
在Angular4开发过程中,数据通信是不可或缺的一部分。组件之间的交互可以通过多种方式实现,包括输入属性(@Input)、输出属性(@Output)、事件发射以及服务共享等方法。本段落将重点讨论如何通过创建并使用共享服务来实现在多个组件间进行数据传递。
首先需要定义一个可以被所有相关组件使用的共享服务类`CommonService`:
```typescript
import { Injectable } from @angular/core;
@Injectable()
export class CommonService {
public dateList: any = [
{ name: 张旭超, age: 20, address: 北京市朝阳区 }
];
constructor() {}
addDateFun(data) {
this.dateList.push(data);
}
}
```
上述代码中,`CommonService`定义了一个公共属性 `dateList` ,用于存储需要共享的数据,并提供一个方法 `addDateFun()` 用来添加新的数据项。
接下来,在使用该服务的组件(如父组件)中通过构造函数注入此服务:
```typescript
import { Component, OnInit } from @angular/core;
import { CommonService } from ./common.service;
@Component({
selector: parent-tag,
templateUrl: parent.component.html,
providers: [CommonService] // 在父组件提供服务实例
})
export class ParentComponent implements OnInit {
public list: any = [];
constructor(private commonService: CommonService) {
this.list = commonService.dateList;
}
ngOnInit() {}
}
```
这里,我们通过在`providers`数组中声明了 `CommonService` ,确保父组件拥有该服务的实例。同时,在构造函数中将从服务获取到的公共属性赋值给当前组件中的变量以供模板使用。
假设还有一个子组件需要访问和修改相同的数据源:
```typescript
import { Component } from @angular/core;
import { CommonService } from ./common.service;
@Component({
selector: child-one-tag,
templateUrl: child-one.component.html
})
export class ChildOneComponent {
public display: boolean = false;
public username: string = ;
public age: number = 20;
public address: string = ;
constructor(public commonService: CommonService) {}
showDialog() { this.display = true; }
hideDialog() { this.display = false; }
addInfoFun() {
let params = { name: this.username, age: this.age, address: this.address };
this.commonService.addDateFun(params);
params = {};
}
}
```
通过这种方式,子组件可以调用`addInfoFun()`方法向共享的数据源添加新的条目。由于所有引用该服务的组件都使用同一个数据实例,因此父组件及其他任何相关联的组件能够实时反映出这些变化。
简而言之,在Angular4中利用共享的服务对象可以在多个不同的视图和逻辑模块间实现高效且直观的数据通信机制,特别适用于需要多处访问同一组动态数据的应用场景。
全部评论 (0)


