angularangular-component-router

Running a code when ever a component is loaded in angular 2 similar to angular 1 app.run


Am starting with angular 2 I have few question like

In angular one i used to define a variable in routing config and based on that variable i wrote a code inside app.run() which will check if that variable is true something should happen. SO what it does was when ever a router is changed it checks that condition.

Now what if i want to achieve same thing in angular 2. we dont have app.run() instead we have bootstrap and is it possible to define user defined variable in router config?

I tried searching but could not find answer for my question. Please let me know if any clarification is required regarding the question which i have asked.

Thank you


Solution

  • When a component is loaded in angular2 the lifecycle OnInit is called - if you want to check something from user defined config whenever a new component is loaded you can write the code inside there, something like:

    import { Component, OnInit } from '@angular/core'
    
    @Component({
        ...
    })
    export class MyComponent implements OnInit {
    
        ngOnInit() {
            // write the check for the config value in here
        }
    }
    

    The only other thing you have to do is import whichever file has your user defined config in it and use that inside the ngOnInit method for each component that you define.

    Another way would be to subscribe to the Location service exported by angular, running the check every time the location url changes. To avoid repeating the subscribe you would need to place this code in your main AppComponent file. The only other thing you would need to do is have a global service that you import into all of your components that contains some sort of flag that can tell you if your config value is set to a certain value.

    import { Component, OnInit } from '@angular/core'
    import { Location } from '@angular/common'
    
    ... METADATA ...
    
    export class AppComponent implements OnInit {
    
        constructor(private location: Location) {}
    
        ngOnInit() {
            this.location.subscribe((value) => {
                // do check in here / set value inside global service
            });
        }