Angular中的组件通信
介绍
在这篇文章中,您将了解在 Angular 中的组件之间传递数据的三种方法,根据具体情况,哪种方法是最好的方法。
1. 从 URL 传递数据
考虑一下我们正在从一个页面导航到另一个页面,其中前一页被破坏并且我们正在登陆另一个页面。 如果要传递的数据不多(例如,对象的 id),我们可以使用 URL 来传递数据。
在 Angular 中有两种通过 URL 传递数据的方法:
- 路由器参数
- 查询参数
如果该参数对于组件是必需的,那么我们必须使用路由器参数。 否则,我们可以使用 查询参数 。
使用路由器参数
路由器参数是必需参数。 我们必须在路由器模块中使用 URL 注册参数,如下所示:
应用路由器.module.ts
const routes: Routes = [
{ path: 'list/:id', component: AppListComponent }
];
在此示例中,list 是路由 URL,:id 是必须通过的路由器参数,AppListComponent 是要安装在该路由上的组件。
通过 routerLink 指令传递路由器参数
<button type="button" [routerLink]="['/list', id]" > Show List </button>
在此示例中,id 是在该组件的代码中初始化的变量,而 /list 是我们要导航的路线。
通过 route 服务传递路由器参数
app.component.ts
id = 28;
constructor (private router: Router) {}
route() {
this.router.navigate(['/list', this.id]);
}
读取路由器参数
以下是如何从路由到的组件中读取路由器参数:
应用程序列表.component.ts
constructor(
private activatedroute: ActivatedRoute
) {
this.activatedroute.params.subscribe(data => {
console.log(data);
})
}
使用查询参数
查询参数是可选参数。 无需为查询参数注册单独的 URL。
应用路由器.module.ts
const routes: Routes = [
{ path: 'list', component: AppListComponent }
];
在此示例中,list 是路由 URL,AppListComponent 是组件。
通过 routerLink 指令传递查询参数
<button
type="button"
[routerLink]="['/list']"
[queryParams]="{id: '24'}"
>
Show List
</button>
在此示例中,id 是键,24 是静态值。 您还可以通过变量传递动态值。
通过 route 服务传递查询参数
app.component.ts
id = 28;
constructor (private router: Router) {}
route() {
this.router.navigate(['/list'], {queryParams: {id: this.id}});
}
读取查询参数
应用程序列表.component.ts
constructor(
private activatedroute: ActivatedRoute
) {
this.activatedroute.queryParams.subscribe(data => {
console.log(data);
})
}
注意:在本文中获取有关Angular路由器参数的更多详细信息。
2. 通过 @Input 和 @Output 传递数据
如果我们想将数据从子组件传递给父组件或父组件到子组件,我们可以使用 @Input 和 @Output。
应用程序-parent.component.html
<app-child [jsonData]="data" (outputData)="data = $event" ></app-child>
这里 data 是在组件代码中初始化的变量。
app-child.component.ts
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-child',
template: ''
})
export class AppChild implements OnInit {
@Input()
jsonData;
@Output()
outputData = new EventEmitter();
constructor() {}
ngOnInit() {
console.log(this.jsonData);
}
emitData(data) {
this.outputData(data);
}
}
通过这种方式,我们可以将数据从孩子传递给父母,也可以从父母传递给孩子。
3. 使用 Observables 通过服务传递数据
如果两个组件是同级的,或者层次结构中组件的级别更远,那么最好使用服务来使用 observables 传递数据。
这个例子使用 RxJS subject 创建一个 observable:
应用服务.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({providedIn: 'root'})
export class AppService {
observer = new Subject();
public subscriber$ = this.observer.asObservable();
emitData(data) {
this.observer.next(data);
}
}
要发出数据,您可以调用此服务的 emitData 方法并获取数据,您必须像这样订阅 subsciber$:
constructor(private appService: AppService) {}
ngOnInit() {
this.appService.subscriber$.subscribe(data => {
console.log(data);
});
}
结论
现在就是这样,三种在 Angular 中的组件之间来回传递数据的方法。 现在继续构建一些很棒的组件!