Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call service method from html file.?

Tags:

angular

Lets explain my code, I am having one component file and one service file

First, From the component I am passing the values to the service file's methods and storing the values as global variable in service file.

Second, I am calling another one method in the component file, and I am trying to access the global variable, what I stored earlier.

My code is below

Component file

import { NewService } from './new.service';



@Component({
selector: 'test',
templateUrl: './passwordPolicy.html',
providers: [FormErrorService]
})
export class TestComponent implements OnInit {

    obj1 = {"val":1,"val2":2};
    obj2 = {"val":1,"val2":2};

    constructor(private ns: NewService,) {

    }
    ngOnInit(){
        this.ns.firstMethod(this.obj1,this.obj1);
    }

    keyCheck(){
        this.ns.secondMethod();
    }

}

Service file

export class NewService{
    Sobj: any;
    Sobj2: any;
    firstMethod(v1,v2){
        this.Sobj = v1;
        this.Sobj2 = v2;        
    }
    secondMethod(){
        console.log(this.Sobj);
        console.log(this.Sobj2);
    }
}

and the template file

<button (click)='keycheck()'>Enter</button>

When clicking the button I am getting console.log with the values.


Now my question is I am trying to the call the service method from the Html file, like as follow

component file

    sMet:any;
    constructor(private ns: NewService,) {
        this.sMet = this.ns.secondMethod;
    }

And the html file is

<button (click)='sMet()'>Enter</button>

but above code is giving service's object are undefined. How to call it.?

Demo

like image 981
mkHun Avatar asked Dec 23 '22 00:12

mkHun


2 Answers

declare the service as public in the component constructor

constructor(public ns: NewService) { }

then you can use it directly in HTML

<button (click)="ns.secondMethod()">button</button>
like image 180
tamim abweini Avatar answered Jan 09 '23 04:01

tamim abweini


You need not use anything like sMet()

Directly use

<button (click)='ns.secondMethod()'>Enter</button>

refer the code at stackblitz

If you want to use some variable, then use in the below way,

sMet = () => this.ns.secondMethod();

And in html,

<button (click)='sMet()'>Enter</button>

If you want to use the same way as described in your demo stackblitz, make the secondMethod() in your testService as an arrow function like below.

   secondMethod = () => {
        console.log(this.Sobj);
        console.log(this.Sobj2);
    }

here is your edited stackblitz code

like image 36
dileepkumar jami Avatar answered Jan 09 '23 02:01

dileepkumar jami