Bird
0
0

Which of the following code snippets correctly implements this conditional logic?

hard🚀 Application Q8 of 15
Angular - HTTP Client
You want your Angular interceptor to add an authentication token only to HTTP requests whose URLs start with 'https://api.example.com/'. Which of the following code snippets correctly implements this conditional logic?
Aif (req.url === 'https://api.example.com/') { const cloned = req.clone({ headers: req.headers.set('Authorization', token) }); return next.handle(cloned); } else { return next.handle(req); }
Bif (req.url.includes('api.example.com')) { req.headers.set('Authorization', `Bearer ${token}`); return next.handle(req); } else { return next.handle(req); }
Cif (req.url.startsWith('https://api.example.com/')) { const cloned = req.clone({ headers: req.headers.set('Authorization', `Bearer ${token}`) }); return next.handle(cloned); } else { return next.handle(req); }
Dif (req.url.indexOf('api.example.com') > 0) { const cloned = req.clone({ headers: req.headers.append('Authorization', token) }); return next.handle(cloned); } else { return next.handle(req); }
Step-by-Step Solution
Solution:
  1. Step 1: Check URL condition

    Use startsWith to match exact URL prefix.
  2. Step 2: Clone request and set header

    Clone request before setting 'Authorization' header.
  3. Step 3: Return modified or original request

    Return cloned request if condition met; else original.
  4. Final Answer:

    if (req.url.startsWith('https://api.example.com/')) { const cloned = req.clone({ headers: req.headers.set('Authorization', `Bearer ${token}`) }); return next.handle(cloned); } else { return next.handle(req); } correctly implements the logic.
  5. Quick Check:

    Use startsWith and clone before modifying [OK]
Quick Trick: Use startsWith and clone request before header set [OK]
Common Mistakes:
MISTAKES
  • Modifying original request headers directly
  • Using includes instead of startsWith
  • Comparing URL with equality instead of prefix
  • Appending header instead of setting it

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes