【发布时间】:2021-12-29 07:14:38
【问题描述】:
我的 Angular 项目中有两个完全独立的元素。第一个显示车牌列表和每个车牌的两个按钮:“查看当前位置”和“查看过去 24 小时的位置”。这两个按钮重定向到同一个组件,该组件根据变量“方法”在地图中显示一些点。单击按钮时,我想将“方法”设置为某个值,但我不知道该怎么做。
我尝试过关于主题/订阅的事情,但对我不起作用。我可能没有正确应用它,因为我对它的工作原理不是很有信心。在我找到的示例中,主题是由一些 @Injectable 提出的,但我正在使用两个 @Component。
谢谢大家。
编辑:我将尝试解释我的尝试。
我有服务
import { Inject, Injectable } from "@angular/core";
import { MatriculasListadoComponent } from "../components/matriculas-listado/matriculas-listado.component";
import { Metodos } from "../models/metodos";
@Injectable({
providedIn: 'root'
})
export class ConexionDataService {
metodoBoton: Subject<Metodos>
constructor() {
this.metodoBoton = new Subject<Metodos>();
}
}
然后我的组件中有一个方法,我想从该方法发送数据,称为单击按钮:
constructor(private matriculaService: MatriculaService, private conexionDataService: ConexionDataService) {
this.dataSource = new MatTableDataSource<Matricula>([]);
}
...
enviarMetodo(metodo:Metodos) {
this.conexionDataService.metodoBoton.next(metodo);
}
我在要接收数据的组件中有这个 NgOnInit
providers: [ListaPosicionesService, DatePipe, ConexionDataService]
...
ngOnInit(): void {
this.conexionDataService.metodoBoton.subscribe(log=> {
this.metodo=log
console.log(log)
})
我将日志显示为“未定义”。可能我做得不好,因为我根本不明白这些服务是如何工作的......
【问题讨论】:
-
请添加更多细节,提供代码 sn-p 这将有助于理解为什么它不起作用。
-
您需要提供您的代码。这是否回答了您的问题:stackoverflow.com/questions/51660156/…
-
@DevangPatel 我已经添加了代码,希望你能帮助我
-
@Anuj.T 代码添加
-
@Videgain 只需将服务中的主题更改为 behaviorSubject。在我的回答中,我分享了如何使用行为主题的演示。
标签: angular angular-components subscribe