Noman
Noman

Reputation: 887

Angular 2 - creating alert in service

I have this alert:

contractorService.ts:

public showConfirm(title: string, message: string, cancelBtnTxt: string, confirmBtnTxt: string, confirmFunc: any, cancelFunc: any): void {
    console.log("confirmFunc: ", confirmFunc);
    const confirm = this.alertCtrl.create({
      title: title,
      message: message,
      buttons: [
        {
          text: cancelBtnTxt,
          handler: () => {
            cancelFunc();
          }
        },
        {
          text: confirmBtnTxt,
          handler: () => {
            confirmFunc();
          }
        }
      ]
    });
    confirm.present();
  }

I have a service, I think I might need to call it from other places. How can I pass in the confirm and cancel functions with parameters.

requestComponent.ts:

public test(): void {
    console.log('test');
}

some other function in requestComponent.ts:

someFunc(): void {
    this.service.showConfirm('title', 'message', 'Cancel', 'OK, this.test, null);
}

The above works, but then I tried:

public test(param: any): void {
    console.log('test: ', param); // param is undefined.
}

someFunc(): void {
    this.service.showConfirm('title', 'message', 'Cancel', 'OK, this.test.bind('test param'), null);
}

but I get: test: undefined

Upvotes: 1

Views: 290

Answers (3)

Xinan
Xinan

Reputation: 3162

You can also try the following:

this.service.showConfirm('title', 'message', 'Cancel', 'OK, () => this.test('test param'), null);

I always feel this is the most elegant way for doing this kind of things.

Upvotes: 1

Amit Chigadani
Amit Chigadani

Reputation: 29705

You should pass the arguments as follows :

this.service.showConfirm('title', 'message', 'Cancel', 'OK', this.test.bind(this, 'Yes'), null);

Notice the parameter this.test.bind(this, 'Yes'). You should be passing this context (component) to the called function, because your test method exists on component.

Upvotes: 1

Noman
Noman

Reputation: 887

this.contractorService.showConfirm("Continue?", "Your credit card will be charged", "Cancel", "OK", this.test.bind(this.test, 'a'), this.cancel);

So I guess we need to pass a function with arguments. Above is working.

Upvotes: 0

Related Questions