How can we pass sling model data to another service class | Community
Skip to main content
Level 2
Oct 1, 2022 11:57 AM UTC
Solved

How can we pass sling model data to another service class

I wanted to pass sling model data to another service class and retrieve the response to sightly via same sling model class. Is there any way?

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
malay_dubeAccepted solution
Employee
Oct 3, 2022 10:41 AM UTC

Hi @vainavee 

Use @inject to adopt the service. Then inside init method call that particular method of that service by passing required inputs from slingmodel. Once you get the data back from service store it in a variable. Create getter of that particular variable. In sightly using use object read the variable.

@Inject
private <Service> service;

private String test = null;

 

@PostConstruct
protected void init() {

test = this.service.<Method>(<required Param>);
}

public void getTest(){

return test;

}

-----------------
Sightly : 
<div data-sly-use.cmp="<slingmodel path>">
<h1> Var : ${cmp.test} </h1>
</div>

 

2 replies

malay_dubeAccepted solution
Employee
Oct 3, 2022 10:41 AM UTC

Hi @vainavee 

Use @inject to adopt the service. Then inside init method call that particular method of that service by passing required inputs from slingmodel. Once you get the data back from service store it in a variable. Create getter of that particular variable. In sightly using use object read the variable.

@Inject
private <Service> service;

private String test = null;

 

@PostConstruct
protected void init() {

test = this.service.<Method>(<required Param>);
}

public void getTest(){

return test;

}

-----------------
Sightly : 
<div data-sly-use.cmp="<slingmodel path>">
<h1> Var : ${cmp.test} </h1>
</div>

 

Translate
Level 4
Oct 1, 2022 1:44 PM UTC

Hi @vainavee ,

 

You can inject the osgi service in your model class and then invoke the method from the service by passing params.

 

@Inject
private MyService myService;

 

@PostConstruct
protected void init() {

String firstName = this.myService.getName(param);
}

 

Refer this for more annotations and details.

https://sling.apache.org/documentation/bundles/models.html 

 

 

Translate