我是角质方面的初学者。我一直面临着从组件中调用组件中的方法的问题,这些方法与组件无关。我在网上学习了很多教程,但还没有找到解决方案。
所以细节是:有两个不相关的组件。第一个组件有一个按钮,如果我单击该按钮,来自第一个组件的字符串应该被发送到第二个组件中的函数,在该函数中它应该将字符串显示到控制台中。但是这里我面临的问题是,函数在单击之前只调用一次,它只显示值"111“,这是默认值。请帮帮我
第一部分:
export class FirstComponent implements OnInit{
constructor(location:Location, private renderer : Renderer2, private element : ElementRef, private router: Router, private httpClient: HttpClient, private servic: MainService) {
}
clickMe() {
this.servic.sendMessage("001");
}
}
第二部分:
export class SecondComponent implements OnInit {
clickEventSubs:Subscription;
constructor(public servic: MainService, private spinner: NgxSpinnerService, private router: Router){}
this.clickEventSubs = this.servic.receiveMessage().subscribe(message => {
this.toggle(message);
})
public toggle(state: string){
console.log(state);
}
}
共享服务:
@Injectable({
providedIn: 'root'
})
export class MainService {
private message = new BehaviorSubject<string>("111");
sendMessage(mess:string) {
this.message.next(mess);
}
receiveMessage(): Observable<any> {
return this.message.asObservable();
}
}
发布于 2022-06-04 17:08:42
当组件之间的关系是子>父-共享日期通过@viewChild()
在第一个组件中,使用@ViewChild()并传递第二个组件名作为参数-
@ViewChild(SecondComponent) secondChildView!: SecondComponent;然后在第一个组件的函数中调用第二个组件的函数-
import {ViewChild} from '@angular/core';
export class FirstComponent implements OnInit{
@ViewChild(SecondComponent) secondChildView!: SecondComponent;
constructor() {}
clickMe() {
this.secondChildView.toggle('001');
}
}每当您调用clickMe函数时,它都会调用第二个组件的切换函数,然后从第一个组件中得到切换函数中的值。
export class SecondComponent implements OnInit {
constructor(){}
public toggle(state: string){
console.log(state);
}
}https://stackoverflow.com/questions/72496791
复制相似问题