How to Get all products assigned to category by category id Magento 2.

You can retrieve all the products assigned to a specific category by category id in Magento 2.

Used interface:
Magento\Catalog\Api\CategoryLinkManagementInterface

Get Method from the interface to fetch a list of all the products, public function getAssignedProducts($categoryId);

<?php
namespace Jesadiya\Product\Model;

use Exception;
use Magento\Catalog\Api\CategoryLinkManagementInterface;
use Magento\Catalog\Api\Data\CategoryProductLinkInterface;

class CategoryProduct
{
    /**
     * @var CategoryLinkManagementInterface
     */
    private $categoryLinkManagement;

    public function __construct(
        CategoryLinkManagementInterface $categoryLinkManagement
    ) {
        $this->categoryLinkManagement = $categoryLinkManagement;
    }

    /**
     * Fetch all Product assigned to Category
     *
     * @param id $categoryId
     * @return CategoryProductLinkInterface[]
     */
    public function getProductByCategory($categoryId)
    {
        $assignedProduct = [];
        try {
            $assignedProduct = $this->categoryLinkManagement->getAssignedProducts($categoryId);
        } catch (Exception $exception) {
            throw new Exception($exception->getMessage());
        }

        return $assignedProduct;
    }
}

Get all the assigned product to a specific category by iterate over a loop from the above method,

$categoryId = "6"; // category id
$categoryAttribute = $this->getProductByCategory($categoryId);
foreach ($assignedProduct as $product){
    echo $product->getSku(). ' ' .$product->getPosition();
}

Output:
Magento\Catalog\Api\Data\CategoryProductLinkInterface[]

The output will be Product SKU, Product Position, category id.