Magento2: redirection from Observer

Yup, i have find a solution by myself by doing a research

If you want to do that then on __construct() function of your class observer,you must inject two classes.

  • First, \Magento\Framework\App\ResponseFactory which responsible for redirection,
  • Another class \Magento\Framework\UrlInterface which will make url for that redirection.
  • Then create object for ResponseFactory ,and using setRedirect($YourUrl)->sendResponse(); redirect to your wished url.

Observer

<?php
namespace [Vendor]\[modulename]\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class [YourClass] implements ObserverInterface
{
    /**
     * @var \Magento\Framework\App\ResponseFactory
     */
    private $responseFactory;

    /**
     * @var \Magento\Framework\UrlInterface
     */
    private $url;

    public function __construct(
        ......
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url,
        ......
    ) {
        $this->responseFactory = $responseFactory;
        $this->url = $url;
    }

    public function execute(Observer $observer)
    {
        $redirectionUrl = $this->url->getUrl('[ModuleName]/[ModuleName]/[[Action]');
        $this->responseFactory->create()->setRedirect($redirectionUrl)->sendResponse();

        return $this;
    }
}

Example:

Here i am write an example of that redirection.

Basically sales_quote_collect_totals_after event,i was try to forcefully redirect to contact us.

Here the observer code:

<?php
namespace Devamit\Mgoto\Observer;
use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;

class Challo implements ObserverInterface {
    protected $_responseFactory;
    protected $_url;

    public function __construct(

        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url
    ) {
        $this->_responseFactory = $responseFactory;
        $this->_url = $url;
    }
  
    public function execute(Observer $observer) {
        $event = $observer->getEvent();
        
            $myfile = fopen("var/log/debug.log", "a+") or die("Unable to open file!");
          fwrite($myfile, 'Amitber',true);
          fclose($myfile);
      // $this->_responseFactory->create()->setRedirect('www.google.com')->sendResponse();
           $customerBeforeAuthUrl = $this->_url->getUrl('contact/index/index');
          $this->_responseFactory->create()->setRedirect($customerBeforeAuthUrl)->sendResponse();
      return $this;
    }
}

injecting the \Magento\Framework\App\ActionFlag $actionFlag and $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);is the way of forcing Magento to stop processing further events and redirect from an observer specially in the case of using predispatch event.

Here is the sample code

public function execute(\Magento\Framework\Event\Observer $observer)
{

    /** @var \Magento\Customer\Controller\Account\LoginPost\Interceptor $controller_action */
    $controller_action = $observer->getData( 'controller_action' );
    $parameters = $controller_action->getRequest()->getParams();
    $session = $this->customerSession;

    if({yourcondition}){


        // setting an action flag to stop processing further hierarchy
        $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);



        /// redirecting back to its referred url
        $observer->getControllerAction()->getResponse()->setRedirect($this->_redirectInterface->getRefererUrl());
        $session->setCustomerFormData($parameters);

    }

    return $this;


}

Above answer is not working for me I have updated my observer code

public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $params = []; 

        // If you want to redirect with data
        // $url = $this->_urlInterface->getUrl('checkout/cart/index',$params);

        $url = $this->_urlInterface->getUrl('checkout/cart/index');

        $observer->getControllerAction()
                    ->getResponse()
                    ->setRedirect($url);
    }