如何从Angular中的另一个组件调用组件的ngOnit函数

问题描述

在这个组件中有一个名为“CreateBugsViewComponent”的组件,我想使用我的另一个组件“ProjectBugsComponent”的ngOnit函数我该怎么做,“CreateBugsViewComponent”的代码写在下面:

import { HttpClient } from '@angular/common/http';
import { Component,OnInit } from '@angular/core';
import { FormControl,FormGroup,Validators } from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { environment } from '../../environments/environment';

@Component({
  selector: 'app-createbugview',templateUrl: './createbugview.component.html',styleUrls: ['./createbugview.component.scss']
})
export class CreatebugviewComponent implements OnInit {
    onbugsubmit(){
    if(this.createbugform.valid)
    {
      this.createbugform.controls['BugsAttachments'].setValue(this.images);
      this.http.post(this.baseURI+'Bugs/Addbug',this.createbugform.value).subscribe(
        (data:any) => {
          this.dialogRef.close();
          //this.changeLocation(),this.snackbar.open(data.message,'✖',{
            duration:4000,horizontalPosition:'center',verticalPosition:'top'
          }),//this.dialog.closeAll(),localStorage.removeItem('ProjectId')/////////////////In this function I want to use ngOnit of  ProjectBugsComponent Component.
        }
      )
    }
  }

如果有任何其他人想要的信息,请在评论中告诉我,我会提供给您。

解决方法

好吧,你问的实际上是一种不好的做法
这种糟糕做法的最短解决方案是:

  1. ProjectBugsComponent 中创建一个静态公共方法(假设我们称之为 uglyMethod()
  2. ngOnInit的{​​{1}}逻辑移出ProjectBugsComponent
  3. uglyMethod() 导入 CreateBugsViewComponent 并调用 ProjectBugsComponent

这可以解决问题,但同样,你问的是一种不好的做法。
一般而言,最佳做法是创建一个服务,将通用逻辑从 ProjectBugsComponent.uglyMethod() 移到那里,并在需要时从两个组件中调用它。

,

将共享逻辑放在一个服务中,并将服务注入到组件中。

共享服务

@Injectable({
  providedIn: 'root',})
export class SharedLogicService {
  sharedFunction(router): void {
    console.log(router.routerState.snapshot.url,'called')
  }
}

ComponentAComponentB

constructor(private router: Router,private sharedLogicService: SharedLogicService){}

ngOnInit() {
  this.sharedLogicService.sharedFunction(this.router);
}
,

最好按照this article来处理组件之间的通信。 Angular 已经有所描述的方法,这个不在列表中。但如果你真的想要,这里有一个例子:

app-layout.component.ts

import { StudentsComponent } from './../students/students.component';
import { Component,OnInit } from '@angular/core';
import { ActivatedRoute,} from '@angular/router';

@Component({
  selector: 'app-layout',templateUrl: './app-layout.component.html',styleUrls: ['./app-layout.component.scss']
})
export class AppLayoutComponent implements OnInit {

  constructor(private route: ActivatedRoute,private studentsC: StudentsComponent) {

  }

  ngOnInit(): void {
    // calling NgOnInit in StudentComponent
    this.studentsC.ngOnInit()
  }

}

students.component.ts

import { Component,Injectable,OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-students',templateUrl: './students.component.html',styleUrls: ['./students.component.scss']
})
//**!!! important to add**
@Injectable({
  providedIn: 'root',})
export class StudentsComponent implements OnInit {

  constructor(private router: Router) { }
  displayedColumns: string[] = ['position','name','weight','symbol'];
  dataSource = ELEMENT_DATA;
  ngOnInit(): void {
    console.log(this.router.routerState.snapshot.url,'called')
  }

}