Adrien Castagliola Adrien Castagliola - 2 months ago 8
jQuery Question

How can i call a service from a directive in Angular 2

I can't call my service from this directive. I use a template with with wizard.js to make a wizard modal form. I'm not sure if it's a angular 2 problem btw.

Here is my directive :

import {Directive,Input, EventEmitter, ElementRef, Output} from '@angular/core';
import {Injectable,Inject} from '@angular/core';
import {Service} from '../../../service/service';

@Directive ({
selector: '[bootstrap-application-wizard]',
providers:[DashboardService]
})

export class BootstrapApplicationWizard {
$el: any;
constructor(
private _service:Service){}

function render(){
wizard.on('submit', function(wizard): void {
this.submit = {'data1': 'John','data2': 'Doe'};
this._service.postData('data',this.submit).subscribe(x=>{
console.log('ok');
});
}

ngOnInit(){
this.render();
}
}


Any ideas ?

Answer

Remove function and replace function () by () =>

 @Directive ({
              selector: '[bootstrap-application-wizard]',
              providers:[DashboardService]
        })

       export class BootstrapApplicationWizard {
          $el: any;
          constructor(private _service:Service){}

          render(){
               wizard.on('submit', (wizard): void => {
                  this.submit = {'data1': 'John','data2': 'Doe'};
                  this._service.postData('data',this.submit).subscribe(x=>{
                          console.log('ok');
                        });
                }

          ngOnInit(){
              this.render();
          }
}
Comments