簡體   English   中英

如何從 Angular 中的另一個組件調用組件的 ngOnit function

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

我在這個組件中有一個名為“ CreateBugsViewComponent ”的組件我想使用我的另一個組件“ ProjectBugsComponent ”的ngOnit function 我該怎么做?“ 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中創建一個 static 公共方法(假設我們稱之為uglyMethod()
  2. ProjectBugsComponentngOnInit的邏輯移出到uglyMethod()
  3. CreateBugsViewComponent導入ProjectBugsComponent並調用ProjectBugsComponent.uglyMethod()

這將解決問題,但同樣,你問的是一種不好的做法。
一般來說,最佳實踐是創建一個服務,將通用邏輯從ngOnInit移到那里,並在需要時從兩個組件中調用它。

將共享邏輯放入服務中,並將服務注入組件中。

共享服務

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

組件 A組件 B

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

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

最好按照這篇文章來處理組件之間的通信。 Angular 已經有描述的方法,這個不在列表中。 但如果你真的想要,這里有一個例子:

應用程序布局.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()
  }

}

學生.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')
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM