如何在Observer事件中获取Response getBody()?


8

在Magento 1中,我可以执行以下操作:

$response = $observer->getEvent()->getControllerAction()->getResponse();
if(!$response) {
   return $this;
 }

$html = $response->getBody(); 

我如何在Magento 2中做同样的事情?

Answers:


6

假设您的模块在 Vendor\Module

如果你想捕捉从响应的HTML,你可以在你的声明事件etc\<area>\events.xml(其中<area>adminhtmlfrontend):

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_front_send_response_before">
        <observer name="vendor_module" instance="Vendor\Module\Model\Observer" shared="false" />
    </event>
</config>

然后在Model\Observer.php

<?php

namespace Vendor\Module\Model;

use Magento\Framework\Event\ObserverInterface;

class Observer implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer) 
    {
        $response = $observer->getEvent()->getData('response');
        if (!$response) return;
        $body = $response->getBody();
    }
}

是的,它现在工作正常,我无法给您+50,因为它没有在24小时内完成。
Pratik
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.