You will have to add below dependency to your class :\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory.
Code will be like this
use Magento\Catalog\Model\CategoryRepository;
....
class
....
protected $categoryCollectionFactory;
public function __construct(
...
CategoryRepository $categoryRepository
...
) {
...
$this->categoryRepository = $categoryRepository;
...
}
public function getSubcategories($category, $levels = 2)
{
if ((int)$levels < 1) {
$parent_category_id = 3;
$categoryObj = $this->categoryRepository->get($parent_category_id);
$subcategories = $categoryObj->getChildrenCategories();
foreach($subcategories as $subcategorie) {
$response[] = [
'name' => $subcategorie->getName(),
'url' => $subcategorie->getUrl()
];
}
return $response;
}