我有我想用来在两个组件之间共享数据的服务(我不想使用queryParams之类的东西,因为我不想在URL栏中显示要共享的数据):
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
public data: any;
setData(param) {
console.log("setting data :");
console.log(param); // param correctly display in console
this.data = param;
}
getData() {
console.log(this.data) // undefined
return this.data;
}
}
我的组件A(发送者):模板
<button (click)="navigateToB(data)">Details</button>
组件
export class ComponentA implements OnInit {
data;
ngOnInit() {
... // defining this.data
}
constructor(private router: Router, public dataService: DataService) { }
navigateToB(data) {
this.dataService.setData(data);
console.log(this.dataService.data); // data correctly displayed in console
this.router.navigate(['ComponentB']);
}
我的组件B(接收者):模板
{{ dataReceived | json }}
Component:
import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { DataService } from '../data-service';
@Component({
selector: 'app-compb',
templateUrl: './compb.component.html',
styleUrls: ['./compb.component.css'],
providers: [DataService]
})
export class ComponentB implements OnInit {
public dataReceived: any;
constructor(public dataService: DataService) {
}
ngOnInit() {
this.dataReceived = this.dataService.getData(); // undefined
}
}
应用程序路由模块:
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' }
,
.
.
.
.,
{
path: 'ComponentB',
component: ComponentB
},
.
.
.
];
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [RouterModule]
})
export class AppRoutingModule { }
如果您在组件级别提供服务,则组件的每个实例都有其自己的服务实例,与其他组件实例所使用的服务不同。
在模块中或至少在公共父组件中提供服务。
自Angular 6起,默认情况下,服务在其装饰器中使用providedIn: 'root'
,该装饰器自动在根模块级别提供服务。那就是您应该使用的:我们现在已经接近Angular 9。