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

How to call ngOnit function of a component from another component in Angular

我在这个组件中有一个名为“CreateBugsViewComponent”的组件,我想使用另一个组件的 ngOnit 函数,它是“ProjectBugsComponent”我该怎么做“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.
        }
      )
    }
  }

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

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

共享服务

@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);
}

嗯,你问的其实是不好的做法
最短的解决方案是:

  1. ProjectBugsComponent 中创建静态 public 方法(假设我们将其命名为 uglyMethod()
  2. ProjectBugsComponentngOnInit的逻辑移出到uglyMethod()
  3. CreateBugsViewComponent 导入 ProjectBugsComponent 并调用 ProjectBugsComponent.uglyMethod()

这会解决问题,但同样,您所要求的是一种不好的做法。
一般来说,最佳实践 将创建一个服务,将通用逻辑从 ngOnInit 移到那里,并在需要时从两个组件调用它。

最好按照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')
  }

}