在Angular 2中,可以通过以下几种方式将数据从一个组件发送到另一个组件:
目标组件(target.component.ts):
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-target',
template: '<p>{{ data }}</p>'
})
export class TargetComponent {
@Input() data: any;
}
源组件(source.component.ts):
import { Component } from '@angular/core';
@Component({
selector: 'app-source',
template: '<app-target [data]="myData"></app-target>'
})
export class SourceComponent {
myData: any = 'Hello, World!';
}
共享服务(data.service.ts):
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
sharedData: any;
}
源组件(source.component.ts):
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-source',
template: '<button (click)="sendData()">Send Data</button>'
})
export class SourceComponent {
constructor(private dataService: DataService) {}
sendData() {
this.dataService.sharedData = 'Hello, World!';
}
}
目标组件(target.component.ts):
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-target',
template: '<p>{{ data }}</p>'
})
export class TargetComponent {
constructor(private dataService: DataService) {}
get data() {
return this.dataService.sharedData;
}
}
路由配置(app-routing.module.ts):
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SourceComponent } from './source.component';
import { TargetComponent } from './target.component';
const routes: Routes = [
{ path: 'source', component: SourceComponent },
{ path: 'target/:data', component: TargetComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
源组件(source.component.ts):
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-source',
template: '<button (click)="sendData()">Send Data</button>'
})
export class SourceComponent {
constructor(private router: Router) {}
sendData() {
this.router.navigate(['/target', 'Hello, World!']);
}
}
目标组件(target.component.ts):
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-target',
template: '<p>{{ data }}</p>'
})
export class TargetComponent {
data: string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.data = this.route.snapshot.paramMap.get('data');
}
}
这些方法可以根据具体的需求选择使用,它们都可以实现在Angular 2中将数据从一个组件发送到另一个组件。
领取专属 10元无门槛券
手把手带您无忧上云