1

I have been reading that I use a sharedservice to share data between 2 components (siblings) but what about sharing functions?

For example I have the following

Service

@Injectable()
export class SharedFunctionService {

  //set these functions from the component in which it resides
  //name scheme: componentname + function name + fn 
  comp1CancelFn: Function;
  constructor() { }
}

comp1

export class comp1 {

    constructor(private sharedFunctionService: SharedFunctionService, 
                private router:Router, private route: ActivatedRoute) {
        this.sharedFunctionService.comp1CancelFn= this.onCancel;
    }
     onCancel():void{
         this.router.navigate(['../'], {relativeTo:this.route});

    }
}

Then I have comp2

 export class comp2{
   constructor(private sharedFunctionService: SharedFunctionService, 
               activatedRoute: ActivatedRoute, private router: Router) { 
    }
   onCancel(){
       this.sharedFunctionService.comp1CancelFn();
   }
 }

So I save the function from comp1 to the service. My expected result is if the cancel function is called from some piece of the html of comp2, it will look for the function in the service and call it. It does this but the problem I run into is all the variables that reside in comp1 are considered undefined (in this case the router but even if i set a simple name string and try to console log it, it is also undefined). Is there any way around this. I came up with my current solution from this source and this source.

Currently using angular 4.4.4 release and the service is in my root providers in app.module

overboard182
  • 190
  • 3
  • 17

1 Answers1

0

You'll probably need to move the variables used by your shared function to the shared service as well.

Richard Medeiros
  • 938
  • 9
  • 18