简体   繁体   English

如何在Route Path Angular2中调用组件的特定功能

[英]How call specific Function of Component in Route Path Angular2

I have to paths, http://localhost:3000/#/activateAccount/1341564455sdfr http://localhost:3000/#/resetPassword/1145gh5w2dd我必须路径, http://localhost:3000/#/activateAccount/1341564455sdfr http://localhost:3000/#/resetPassword/1145gh5w2dd

and the code into the app.routes.ts File is和 app.routes.ts 文件中的代码是

{ path: 'activateAccount/:temp_id', component: FrontGeneralComponent },
{ path: 'resetPassword/:reset_id', component: FrontGeneralComponent },

What I want that use only a Single component for both of these above URLs but I don't know how to call a specific function into the Component,我希望对上述两个 URL 仅使用单个组件,但我不知道如何将特定函数调用到组件中,

Suppose I have 2 functions into the Component, 1 for Account Activation and other for password reset, But how it can call that from routes call.假设我在组件中有 2 个函数,1 个用于帐户激活,另一个用于密码重置,但是它如何从路由调用中调用它。 Note: both are in the same component.注意:两者都在同一个组件中。 and I want to call them based on routes path.我想根据路由路径调用它们。

function activateAccount()
{
    // Code will go here to activate based on temp. id
}

function resetPassword()
{
    // Code will go here to reset password based on temp. id
}

to get the parameters of the activated route, you can inject activatedRoute.要获取激活路由的参数,可以注入activatedRoute。

You can make your component implements 'OnInit' interface from @angular/core, and then use the "ngOnInit" method which will be called by Angular when he creates your component.您可以让您的组件从@angular/core 实现“OnInit”接口,然后使用“ngOnInit”方法,该方法将在 Angular 创建您的组件时调用。

In this method, you can check your parameters and according to them, call one function of another.在此方法中,您可以检查参数并根据它们调用另一个函数。 Something like that :类似的东西:

class myComponent implement OnInit {
   
   constructor (private activatedRoute: ActivatedRoute) {}

   ngOnInit () {
      this.activatedRoute.params.subscribe((params) => {
          if (params['temp_id']) { this.activateAccount(); }
          else if (params['reset_id']) { this.resetPassword(); }
      });
   }

}

Finally, I warn you that having a component like that is not a good practice.最后,我警告你,拥有这样的组件不是一个好习惯。 A component is suppose to do one thing and one only.假设一个组件只做一件事。 You are creating a single component which have multiple behavior according to the route.您正在创建根据路线具有多种行为的单个组件。 It would be better to have two different components.最好有两个不同的组件。 Or at least a parent component and some children, one which can activate an account, the other to reset a password.或者至少有一个父组件和一些子组件,一个可以激活帐户,另一个可以重置密码。

Hope that helps希望有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM