我正在尝试从嵌套在 <router-outlet>
中的子组件调用父组件标签。就我而言,我试图调用 timer.start()
启动位于父组件内的计时器的函数。
我已经通过导入到子项成功调用了父项的函数,但是计时器不工作。我试图记录指示计时器是否正在运行的标志,它已经在 true
中了。条件。
代码如下:
import { NavbarComponent } from './../navbar/navbar.component'; /* This is the parent component */
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-css-inoculation-scoring',
templateUrl: './css-inoculation-scoring.component.html',
styleUrls: ['./css-inoculation-scoring.component.scss'],
providers: [ NavbarComponent ]
})
export class CSSInoculationScoringComponent implements OnInit {
constructor(private _service: DataModelService, private _navbar: NavbarComponent) {}
ngOnInit() {
this.vessel.getVessel();
this._navbar.timer.start();
}
}
这是 timer.start 函数:
start: () => {
this.timer.isTicking = true;
this.timer.startTime();
}
timer.start函数还调用了另一个函数,这里是timer.startTimer()函数:
startTime: () => {
if (this.timer.isTicking) {
let hour = parseInt(this.timer.hour, 10);
let minute = parseInt(this.timer.minute, 10);
let second = parseInt(this.timer.second, 10);
second += 1;
if (second > 60) {
minute += 1;
second = 0;
}
if (minute > 60) {
hour += 1;
minute = 0;
}
this.timer.second = second < 10 ? `0${second}` : `${second}`;
this.timer.minute = minute < 10 ? `0${minute}` : `${minute}`;
this.timer.hour = hour < 10 ? `0${hour}` : `${hour}`;
setTimeout(this.timer.startTime, 1000);
}
}
我想改变 isTicking
的值通过服务,并返回可观察的。我有另一个类似的案例,它的工作。但是在timer.startTime()
函数还修改了定时器的属性。我还应该为此使用服务吗?还是有其他方法?
最佳答案
我假设您想使用父级的上下文调用父级的方法。 我建议避免将组件作为服务传递,因为如果有需要共享的功能——它应该是一项服务。但是如果一个 child 需要在 parent 的上下文中触发 parent 的方法,那么您可以将它传递给 child 并从那里调用 if。
// child component
import { Component, EventEmitter, OnInit } from '@angular/core';
@Component({
selector: 'app-css-inoculation-scoring',
templateUrl: './css-inoculation-scoring.component.html',
styleUrls: ['./css-inoculation-scoring.component.scss'],
})
export class CSSInoculationScoringComponent implements OnInit {
@Output() startTimer: EventEmitter<any> = new EventEmitter();
constructor(private _service: DataModelService)
ngOnInit() {
this.vessel.getVessel();
this.startTimer.emit();
}
}
// PARENT COMPONENT TEMPLATE
<targeting
(startTimer)="timer.start()">
</targeting>
关于javascript - 如何从子组件调用父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54015465/