angular - 从组件服务之间的共享数据中获取数据时未定义数据
问题描述
我有我的服务,我想用它在我的两个组件之间共享数据(我不想使用 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 }}
零件 :
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。
推荐阅读
- amazon-web-services - aws批处理作业的运行时间
- delphi - 如何在铬 cef3 中获取网站错误计数
- ios - Swift:从金额文本中获取货币符号
- java - java配置的spring mvc拦截器不起作用
- post - 如何在 gitlab 中触发特定作业
- mysql - 通过 mysql 删除 mediawiki 垃圾邮件用户
- java - Travis CLI 上的 Spring Boot 测试失败并出现异常:com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
- angular - 向 Angular Service Worker 响应添加标头
- html - 尝试向数据库图像添加线性渐变,我可以在 css 上使用 db 图像吗?
- java - Kafka:重新平衡后如何为消费者获取先前的分区