If your component runs in one/one.app
container(SF1 or LEX - Record Detail page ), Tushar Sharma's solution will work for you, because the it is handled by the one/one.app
itself.
Below is the statement on the doc:
e.force:XXX event is handled by the one.app container.
It’s supported in Lightning Experience and Salesforce1 only. If used
outside of Lightning Experience or Salesforce1, this event won’t be
handled automatically. To use this event outside of one.app, create
and wire up an event handler of your own.
One approach is that,just check whether the e.force:navigateToSObject
is available or not(which won't inside a standalone app), and switch the navigation logic.
Component:
<aura:component controller="contactSearch" implements="force:appHostable" >
<aura:attribute access="public" name="maxResults" type="Integer" default="10" />
<aura:attribute name="contacts" type="Contact[]" />
<ul>
<aura:iteration items="{!v.contacts}" var="contact indexVar="index">
<li class="minli">
<h3>
<a onclick="{!c.navigateToRecord}" style="width:100%;" data-index="{!index}">{!contact.Name}</a>
</h3>
</li>
</aura:iteration>
</ul>
</aura:component>
Controller:
({
navigateToRecord : function(component, event, helper) {
var idx = event.target.getAttribute('data-index');
var contact = component.get("v.contacts")[idx];
var navEvent = $A.get("e.force:navigateToSObject");
if(navEvent){
navEvent.setParams({
recordId: contact.Id,
slideDevName: "detail"
});
navEvent.fire();
}
else{
window.location.href = '/one/one.app#/sObject/'+contact.Id+'/view'
}
}
})
Another approach is, you can wire up an event handler of your own for the e.force:navigateToSObject
, like this:
Component:
<aura:component controller="contactSearch" implements="force:appHostable" >
<aura:attribute access="public" name="maxResults" type="Integer" default="10" />
<aura:attribute name="contacts" type="Contact[]" />
<aura:handler event="force:navigateToSObject" action="{!c.navigateToRecord}"/>
<ul>
<aura:iteration items="{!v.contacts}" var="contact indexVar="index">
<li class="minli">
<h3>
<a onclick="{!c.viewRecord}" style="width:100%;" data-index="{!index}">{!contact.Name}</a>
</h3>
</li>
</aura:iteration>
</ul>
</aura:component>
Controller:
({
viewRecord : function(component, event, helper) {
var navEvent = $A.get("e.force:navigateToSObject");
var idx = event.target.getAttribute('data-index');
var contact = component.get("v.contacts")[idx];
if(navEvent){
navEvent.setParams({
recordId: contact.Id,
slideDevName: "detail"
});
navEvent.fire();
}
},
navigateToRecord : function(component, event, helper) {
var recordId = event.getParam("recordId");
window.location.href = '/one/one.app#/sObject/'+recordId+'/view';
},
})
/one/one.app
container ?