2

This is just me trying to get an understanding of the lifecycle and try and perform some logic before loading the component so I found the CanActivate Annotation.

I have a function in the Component that I want to call so I need the Component; I have injected it... it seems overly complex.

// HomeComponent Component
@Component({
  selector: 'HomeComponent',
  template: '<h2>HomeComponent Us</h2>'
})
@CanActivate((next,prev) => {

  let injector: any = Injector.resolveAndCreate([HomeComponent]);
  let theComponent: HomeComponent = injector.get(HomeComponent);

  return theComponent.canActivate(next,prev)
})

class HomeComponent {
  data = {}
  myresolver: any

  constructor() {
    console.log("in constructor", this.data)
  }

  setData(data: any) {
    this.data = data
  }

  canActivate(nextInstr, currInstr) {
      console.log("in my resolver");
      var that = this;
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          var data = { data: "Aaron" };
          that.setData(data)
          resolve(data);
        }, 2000)
      });
    }

}
Aaron Saunders
  • 33,180
  • 5
  • 60
  • 80
  • 2
    Well if you look at the documentation note at https://angular.io/docs/ts/latest/api/router/CanActivate-var.html it clearly mentions the reason and it makes sense. CanActivate is called before the Component is instantiated and hence invoking a function inside the Component seems incorrect. – Chandermani Dec 26 '15 at 02:45

1 Answers1

2

In fact you can't since processing within the annotation is called right before instantiating (or not) the component.

I guess that you want to use the resolve feature of Angular1 router into Angular2. In fact, such feature isn't supported yet. For more details you can have a look at this issue in the Angular github:

The two following links give you some workarounds for your use case:

Hope it helps you, Thierry

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • i guess i was looking to keep the logic for accessing the controller in the controller but I guess that is not the correct pattern... I did see the approach of injecting a service that contained the loging into the canActivate method but was looking for something different... thanks – Aaron Saunders Dec 29 '15 at 02:48
  • Yes referencing a service from the CanActivate function is possible but not the reference of the component is attached on. FYI there is no more the concept of controller in Angular2 ;-) – Thierry Templier Dec 29 '15 at 09:42