Expand my Community achievements bar.

SOLVED

Call Model Inside Service

Avatar

Level 4

Hi,

We are trying to create a filter component (that filters results based on tags). Query should accept parent page from which the pages will be shown as a list. We got the value that is given as input on the component. We got it using Sling Model. We are trying to pass it to Service class, in order to pass it to Query. But, when we call the methods of model, all return null. Thanks!

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi @AD-Engineer 

 

You can call the service class inside the Sling Model using below annotation where QueryResultsService is a custom service that is implemented to filter out the results based on the tags.

 

@OSGiService
private QueryResultsService queryService;

 Which one is returning null?

View solution in original post

6 Replies

Avatar

Correct answer by
Community Advisor

Hi @AD-Engineer 

 

You can call the service class inside the Sling Model using below annotation where QueryResultsService is a custom service that is implemented to filter out the results based on the tags.

 

@OSGiService
private QueryResultsService queryService;

 Which one is returning null?

Avatar

Level 4

Hi @Asutosh_Jena_ 

Thanks for your reply!

I tried this one, but this returns null too.

The errorr: 

org.apache.sling.scripting.sightly.SightlyException: org.apache.sling.api.SlingException: Cannot get DefaultSlingScript: Identifier com.project.core.models.Filter cannot be correctly instantiated by the Use API

 

Thanks!

Avatar

Community Advisor
Can you psate your model class code here? I believe there are few mandatory fields which are not injected during sling model instantiation. You can make the class as optional and try it out.

Avatar

Level 4
@Asutosh_Jena_ actually I need to call Sling Model from servelt, so I can send as a parameter the path. This is the idea. To get the path from component, get it with Sling model, then send it to Servlet.

Avatar

Community Advisor

@AD-Engineer 

You can adapt a request or a resource to a SlingModel.

SlingModel model = request.adaptTo(SlingModel.class);

 

Now from the model you can read the value as required. But as per the error you have mentioned above some mandatory fields are not injected to sling model which is why you are getting the error. So make sure you are passing all the required fields. Also make the class default injection strategy as optional to complete the instantiation without any error.

 

Thanks!

Avatar

Level 4

Hi @Asutosh_Jena_,

I do not want to access Service from Sling Model, but Sling Model from Service. Thanks!