I recently started diving into Angular 4, starting with Angular 1.5. I work with custom routes and pull API data from a service into a user component.
The component seems to remain static, unlike the controllers in 1. *, where they were updated for each request.
Is there anyway the ngOnInit function called with every new route request?
My custom component class:
// url structure: /user/:id export class UserComponent implements OnInit { constructor(private route: ActivatedRoute) {} ngOnInit() { // doesn't log new id on route change let id = this.route.snapshot.params['id']; console.log(id); this.route.params .switchMap(params => this.userService.getUser(params['id'])) .subscribe(user => { // logs new id on route change let id = this.route.snapshot.params['id']; console.log(id); this.user = user }); } }
UPDATE
Found a solution that I think works best for my scenario. Based on a few answers and comments on my question and further investigation, signing up for a route seems to be a way out. Here is my updated component:
export class UserComponent { user; id; constructor( private userService: UserService, private route: ActivatedRoute ) {} ngOnInit() { this.route.params .subscribe(params => this.handleRouteChange(params)); } handleRouteChange(params) { this.id = params['id']; switch (this.id) { case '1': console.log('User 1'); break; case '2': console.log('User 2'); break; case '3': console.log('User 3'); break; } this.userService.getUser(this.id). subscribe(user => this.user = user); } }
source share