In Magento, it is difficult to call $this->getUrl() by default in plugin or observer file. So whenever you need to call the getUrl() function of Magento in the plugin or observer file, you'd be required to pass dependency as Magento\Framework\URL Interface to construct() method.
public function __construct( \Magento\Framework\UrlInterface $urlBuilder ) { $this->urlBuilder = $urlBuilder; }
In plugin or observer function, we can get getUrl() with the help of below mentioned method,
$this->urlBuilder->getUrl(‘sales/order/view’, [‘order_id’ => 54]);
Now, run the below command for get effect of our dependancy injection to code
php bin/magento setup:di:compile
The output of the above URL will be:
http://{yoururl.com}/admin/sales/order/view/order_id/54/
Also read: How to Encode and Decode URL in Magento 2?