【问题标题】:How to call ngOnit function of a component from another component in Angular如何从Angular中的另一个组件调用组件的ngOnit函数
【发布时间】:2021-08-19 15:37:16
【问题描述】:

我在这个组件中有一个名为“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.
        }
      )
    }
  }

如果有任何其他人想要的信息,请在我将为您提供的 cmets 中告诉我。

【问题讨论】:

    标签: angular angular-material angular-components ngoninit


    【解决方案1】:

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

    共享服务

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

    【讨论】:

    • 你能告诉我如何做这个共享逻辑服务吗????
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      最好关注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')
        }
      
      }
      

      【讨论】:

      • 但它会导致我产生角度循环依赖,这对我的代码不利。
      • 这仍然无法正常工作并显示 Angular 依赖警告......
      猜你喜欢
      • 2020-05-02
      • 2019-02-06
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 2020-04-03
      • 1970-01-01
      • 2019-02-24
      • 1970-01-01
      相关资源
      最近更新 更多