I think it would be better understood by going to basics - by understanding difference between lightning and visualforce.
- Visualforce to apex is synchronous transaction, thus when pageReference object from apex is returned to a visualforce action, it will perform navigation.
- Lightning to apex is asynchronous transaction, thus all the data transfer takes place through serialization and deserialization.
Reason for your code not navigating:
Apex
PageReference
object is not serializable and so it cannot be returned in
@AuraEnabled methods. If you want to test it, you can try System.debug(JSON.serialize(Page.MyPageName));
in anonymous apex - this will throw the same error.
Solution:
Lightning javascript has its own pageReference object api which can be used along with lightning:navigation for navigation purposes.
You can use below JS for your navigation:
component.find("navService").navigate({
"type": "standard__recordPage",
"attributes": {
"recordId": "001xx000003DGg0AAG",
"objectApiName": "PersonAccount",
"actionName": "view"
}
})
and in aura cmp file:
<lightning:navigation aura:id="navService"/>
As an alternative, you can return url string from apex:
@AuraEnabled
public static String redirect(String recordId) {
// create pagereference
return pageRef.getUrl();
}
Then in controller.js:
component.find("navService").navigate({
"type": "standard__webPage",
"attributes": {
"url": "/../..." // url returned from apex
}
})