【问题标题】:implementing relevant life cycle hook实现相关的生命周期钩子
【发布时间】:2020-11-05 17:59:26
【问题描述】:

我对在我的 Angular 应用程序中使用相关的生命周期挂钩感到困惑。我有两个组件,我试图在这两个组件之间导航。我能够从第一个组件导航到第二个组件。但是当我试图从第二个组件导航到第一个组件时。它不能正常工作。请指导我。

我想将“golbalvaue”变量从 secondComponent 发送到 FirstComponent,并在“globalvalue”传输到 FirstComponent 后立即实施一个方法。完成必须实现的生命周期钩子。我能够从 SecondComponent 导航到 FirstComonent。 注意:我可以将它从 SecondComponent 导航到 FirstComponent。问题是我无法访问该变量。 SecodComponent 仅在 FirstComponent 中的事件被触发时才启动。 SecodComponent 启动后,我想触发一个导航到 FirstComponent 的事件。我可以在哪个生命周期钩子中访问变量

第一个组件

import {Router} from '@angular/router';
globalvalue: string;
testvalue: string;

export class FirstComponent implements OnInit, AfterViewInit {

constructor(private route: Router){}


 ngAfterViewInit() {
    this.globalvalue = this.route.getCurrentNavigation().extras.state.globalvalue;
    this.source.addFilter({field: 'test', search: this.globalvalue});
  }

onChange(event) {
    const testdata = event.data.testdata;
      this.route.navigate(['/components/SecondComponent'], {state: {testvalue: testvalue},  fragment: 'testing'});
  }
 }

第二个组件

globalvalue: string;
testvalue: string;

export class FirstComponent implements OnInit, AfterViewInit {

constructor(private route: Router){
this.testvalue = this.router.getCurrentNavigation().extras.state.testvalue;
}

  ngAfterViewInit() {
    this.searchService.onSearchSubmit()
      .subscribe((data: any) => {
        this.globalvalue = data.term;
        this.route.navigate(['/components/First-component'], {state: {globalvalue: this.globalvalue}});
      });
  }

}

【问题讨论】:

  • 你的方法不正确。根据您的需要,有多种方法可以解决此问题。您能否分享您的路线和模块代码以及这方面的任何特定需求。

标签: angular


【解决方案1】:

您可以在路由 url 数组本身中传递 {state: {globalvalue: this.globalvalue}} 作为第二个值

this.route.navigate(['/components/First-component', {state: {globalvalue: this.globalvalue}}]);

然后您可以从constructorngOninit 或您的愿望访问路由参数;)

将 globalValue 发送到其他路由的组件

export class ThirdComponent {
  constructor(
    private router: Router,
  ) {
    this.returnItem();
  }

  returnItem() {
    setTimeout(() => {
      let globalValue = 'Test'
      this.router.navigate(['second', {
        globalValue
      }])
    }, 2000);
  }
}

捕获参数值的组件

export class SecondComponent {
  constructor(private route: ActivatedRoute) {
    this.route.params.subscribe(data => {
      this.logValue(data)
    });
  }

  logValue(data) {
    console.log(data);
  }

}

工作stackblitz

在提供的 stackblitz 中检查 secondthird 组件

【讨论】:

  • 嗨,我可以将它从 SecondComponent 导航到 FirstComponent。问题是我无法访问该变量。 SecodComponent 仅在 FirstComponent 中的事件被触发时才启动。 SecodComponent 启动后,我想触发一个导航到 FirstComponent 的事件。我可以在哪个生命周期钩子中访问变量?
  • @rja 这就是提供的堆栈闪电战中发生的事情。在 stackblitz 中,我在从第三个组件路由到第二个组件时发送一个值。并在第二个组件中捕获价值
  • @rja 在提供的 stackblitz 中,单击 Third Page 链接并等待 2 秒。它将使用参数自动重定向到Other Page(Secod Component)。重定向后检查控制台;)
猜你喜欢
  • 2020-01-15
  • 2017-11-22
  • 1970-01-01
  • 1970-01-01
  • 2018-03-13
  • 2018-08-30
  • 2016-08-26
  • 1970-01-01
相关资源
最近更新 更多