Suppose there're two systems $A$ and $B$, if we're in a pure state $|\psi\rangle\in\mathbb{H}_a\otimes\mathbb{H}_b$. Let $\hat A$ be an operator acting on $\mathbb{H}_a$ and $|\psi\rangle=\sum_{i,j}\psi_{i,j}|a_i\rangle|b_j\rangle$. The expectation value of A with respect to the state $|\psi\rangle$ can be calculated as $$ \langle A\rangle_{\psi}= Tr_{\mathbb{H}_a\otimes\mathbb{H}_b}(A|\psi\rangle\langle\psi|)=\sum_{i,j}\langle a_i|\langle b_j|A\otimes\mathbb{1}_B|\psi\rangle\langle\psi|a_i\rangle|b_j\rangle=... $$
I'm very confused about where these two equalities coming from? In particular, where does the term $|\psi\rangle\langle\psi|$ in the sum come from? Can I understand its function as generating a $\psi$ matrix with different constants $\psi_{i,j}$?