要在Angular 6中使用服务在组件之间传递对象,可以按照以下步骤操作:
data.service.ts
的新服务:import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
private data: any;
setData(data: any) {
this.data = data;
}
getData() {
return this.data;
}
}
DataService
并使用它来设置和获取数据。例如,在发送数据的组件中:import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-sender',
template: `
`
})
export class SenderComponent {
constructor(private dataService: DataService) {}
sendData() {
const data = { name: 'John', age: 30 };
this.dataService.setData(data);
}
}
DataService
并使用它来获取数据。例如,在接收数据的组件中:import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-receiver',
template: `
Received Data:
Name: {{ receivedData?.name }}
Age: {{ receivedData?.age }}
`
})
export class ReceiverComponent {
receivedData: any;
constructor(private dataService: DataService) {
this.receivedData = this.dataService.getData();
}
}
DataService
:import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { SenderComponent } from './sender.component';
import { ReceiverComponent } from './receiver.component';
import { DataService } from './data.service';
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent, SenderComponent, ReceiverComponent],
providers: [DataService],
bootstrap: [AppComponent]
})
export class AppModule {}
AppComponent
中使用SenderComponent
和ReceiverComponent
:import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
Data Transfer using Service
`
})
export class AppComponent {}
这样就完成了使用服务在Angular 6中传递对象的示例。当点击"Send Data"按钮时,数据将被发送到DataService
,然后在ReceiverComponent
中获取并显示。