[SalesForce] Cannot read property ‘navigateToSObject’ of undefined in Lightning

I am developing a Lightning component that lists related Contacts. I would like to make it so that when you click on the name of a related contact, then it will navigate to that contact's record. Here is the component:

<aura:component implements="force:appHostable">
     <aura:attribute name="RelatedContact" type="Contact"/>
     <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
     <ui:outputText value="{!v.RelatedContact.Name}" click="{!goToContact}"/>
 </aura:component>

In my controller I have the method goToContact as follows

goToContact : function(component, event, helper) {
    sforce.one.navigateToSObject(component.get("v.RelatedContact.Id"));
}

and the method doInit as follows

doInit : function(component, event, helper){
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');  
    script.src = "/soap/ajax/32.0/connection.js"; 
    script.type = 'text/javascript';
    script.key = "/soap/ajax/32.0/connection.js"; 
    script.helper = this;
    script.id = "script_" + component.getGlobalId();
    head.appendChild(script);

    var script2 = document.createElement('script');
    script2.src = "/soap/ajax/32.0/apex.js"; 
    script2.type = 'text/javascript';
    script2.key = "/soap/ajax/32.0/apex.js"; 
    script2.helper = this;
    script2.id = "script2_" + component.getGlobalId();
    head.appendChild(script2);
},

Everything appears to load properly, however, when I click on the name a pop up gives me this message

Something has gone wrong. Cannot read property 'navigateToSObject' of undefined.
Please try again.

Best Answer

You will need to fire the event .Lightning is Event driven and different than visualforce .

Use the below event

goToContact : function (component, event, helper) {
 var navEvt = $A.get("e.force:navigateToSObject");
   navEvt.setParams({
     "recordId": component.get("v.RelatedContact.Id"),
     "slideDevName": "related"
   });
   navEvt.fire();
}

Also to fetch all contacts I would use an AuraEnabled apex class to feed the data to the Front end and not use ajax call as you did .

Related Topic