Two NYPD detectives assigned to the Staten Island District Attorney’s office had been watching Goepel and Cosentino for an ongoing drug investigation, sources said.

One detective, a 26-year veteran, approached the rear of the vehicle on foot while his partner, a 20-year veteran, walked to the front of the car, police said.

Goepel, who was driving, threw the car into reverse and then slammed it into drive, striking the 20-year veteran, police said.

Out of self-defense, the officer — hit in his right knee, arm and hand — squeezed off four rounds from his service Glock 9mm, according to police.

One bullet pierced the windshield and grazed Goepel’s head, while Cosentino was injured by the shattering glass, police said.

The duo then fled while the injured cop and his partner remained at the scene awaiting backup and an ambulance.

Goepel and Cosentino were caught within minutes about a mile away on Forest Hill Road, near the rear of the College of Staten Island campus, by an Anti-Crime team responding to the shooting, sources said.

Inside the car, which is registered to Cosentino’s father, cops recovered a quantity of cocaine and at least 30 Oxycontin pills, sources added.

The two officers were taken to Staten Island University Hospital, where the injured officer was treated for his injuries. His partner was also examined after suffering chest pains during the fracas, sources said.

The injured officer who opened fire passed an on-scene sobriety test, which is now given to all cops involved in shootings.

Goepel and Cosentino were taken to Richmond University Medical Center.

Both perps had previously been busted together on Dec. 21 for drug dealing, sources said.

Goepel’s other priors include a June 2009 bust for aggravated harassment and a September 2007 arrest for misdemeanor drug possession, sources added.

Charges pending against the two suspects include assault and drug possession.