gmostert / ng2-breadcrumb

This is an angular 2 component that creates a breadcrumb trail. It hooks into the angular2/router, to dynamically build up the crumb trail once a component is routed to.
MIT License
102 stars 81 forks source link

Using Service to get user friendly name in getNameForUser method for addCallbackForRouteRegex function. #66

Closed meenakshik-optimus closed 7 years ago

meenakshik-optimus commented 7 years ago

I am using the following code to give a friendly name for the user id:

breadcrumbService.addCallbackForRouteRegex('/user-profile/[0-9]*$', this.getNameForUser); getNameForUser(id:string):string { // Here i want to use service to fetch user name. username = this.userDetailService.getUserName(id); // userDetailService is given in the constructor return username ; }

I am getting the following error: TypeError: Cannot read property 'userDetailService' of undefined at webpackJsonp.582.AppComponent.getNameForUser

Is there any way to user external services in the getNameForUser method

beaverusiv commented 7 years ago

This: getNameForUser(id:string):string { Needs to be: getNameForUser = (id:string):string => {

Then it will work. The problem is you're passing a function into the breadcrumbService which is losing your 'this' context of the component you call it from.

meenakshik-optimus commented 7 years ago

Ok, thanks.

aguerere commented 7 years ago

I ran into this same problem and thankfully saved the day by following the instructions above. This should be included in the readme as a heads up, even if the issue has nothing to do with the breadcrumb itself. Thank you!