Police in Brooklyn say the officer is lucky to be alive after he was cornered in a narrow entryway by two men armed with a semiautomatic weapon.
The officer shot and killed one of the suspects, and the other is under arrest.
It all happened at a three-story apartment building at 193 Knickerbocker Avenue in the Bushwick section.
Police say the undercover officer was investigating illegal gun sales and was about to make a purchase from one man when another man ran down the stairs and pointed the weapon at the officer.
The officer opened fire, killing the 31-year-old suspect.
The 22-year-old who was about to sell the officer the illegal weapon grabbed the weapon from the dead man and raced upstairs to try to hide it on the roof.
He was later arrested.
The undercover officer was not hurt and no bystanders in the apartment building at the corner of Jefferson were injured.
Police are investigating whether the two suspects had planned to rob the officer.
The surviving suspect is at the 83rd Precinct awaiting charges.