Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions packages/common/http/src/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,15 @@ export class HttpInterceptorHandler implements HttpHandler {

handle(initialRequest: HttpRequest<any>): Observable<HttpEvent<any>> {
if (this.chain === null) {
const parentHandler = this.injector.get(HttpHandler, null, {skipSelf: true});
const isDelegating = parentHandler !== null && this.backend === parentHandler;
const rootInterceptorFns = this.injector.get(
HTTP_ROOT_INTERCEPTOR_FNS,
[],
isDelegating ? {self: true} : undefined,
);
const dedupedInterceptorFns = Array.from(
new Set([
...this.injector.get(HTTP_INTERCEPTOR_FNS),
...this.injector.get(HTTP_ROOT_INTERCEPTOR_FNS, []),
]),
new Set([...this.injector.get(HTTP_INTERCEPTOR_FNS), ...rootInterceptorFns]),
);

// Note: interceptors are wrapped right-to-left so that final execution order is
Expand Down
16 changes: 12 additions & 4 deletions packages/common/http/src/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,15 @@ export function provideHttpClient(
featureKinds.has(HttpFeatureKind.CustomXsrfConfiguration)
) {
throw new Error(
ngDevMode
? `Configuration error: found both withXsrfConfiguration() and withNoXsrfProtection() in the same call to provideHttpClient(), which is a contradiction.`
: '',
`Configuration error: found both withXsrfConfiguration() and withNoXsrfProtection() in the same call to provideHttpClient(), which is a contradiction.`,
);
}

const hasBackendOverride =
featureKinds.has(HttpFeatureKind.Fetch) || featureKinds.has(HttpFeatureKind.Xhr);
if (featureKinds.has(HttpFeatureKind.RequestsMadeViaParent) && hasBackendOverride) {
throw new Error(
`Configuration error: withRequestsMadeViaParent() cannot be combined with withFetch() or withXhr() in the same call to provideHttpClient().`,
);
}
}
Expand Down Expand Up @@ -267,6 +273,8 @@ export function withJsonpSupport(): HttpFeature<HttpFeatureKind.JsonpSupport> {
* "bubble up" until either reaching the root level or an `HttpClient` which was not configured with
* this option.
*
* This feature is incompatible with the `withFetch` and `withXhr` features.
*
* @see [HTTP client setup](guide/http/setup#withrequestsmadeviaparent)
* @see {@link provideHttpClient}
* @publicApi 19.0
Expand All @@ -282,7 +290,7 @@ export function withRequestsMadeViaParent(): HttpFeature<HttpFeatureKind.Request
'withRequestsMadeViaParent() can only be used when the parent injector also configures HttpClient',
);
}
return handlerFromParent;
return handlerFromParent!;
},
},
]);
Expand Down
169 changes: 163 additions & 6 deletions packages/common/http/test/provider_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,14 @@ import {
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {EMPTY, Observable, from} from 'rxjs';
import {tap} from 'rxjs/operators';

import {HttpInterceptorFn} from '../src/interceptor';
import {HTTP_ROOT_INTERCEPTOR_FNS, HttpInterceptorFn} from '../src/interceptor';
import {
HttpFeature,
HttpFeatureKind,
provideHttpClient,
withFetch,
withInterceptors,
withInterceptorsFromDi,
withJsonpSupport,
Expand Down Expand Up @@ -439,30 +441,172 @@ describe('provideHttpClient', () => {
req.flush('');
});

it('should be able to connect to a legacy-provided HttpClient context', () => {
it('should include root interceptors in independent child contexts', () => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [provideLegacyInterceptor('parent')],
providers: [
provideHttpClient(...commonHttpFeatures),
{
provide: HTTP_ROOT_INTERCEPTOR_FNS,
useValue: makeLiteralTagInterceptorFn('root'),
multi: true,
},
provideHttpClientTesting(),
],
});

const child = createEnvironmentInjector(
[
provideHttpClient(withInterceptors([makeLiteralTagInterceptorFn('child')])),
{
provide: HttpBackend,
useFactory: () => inject(HttpBackend, {skipSelf: true}),
},
],
TestBed.inject(EnvironmentInjector),
);

child.get(HttpClient).get('/test', {responseType: 'text'}).subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/test');
expect(req.request.headers.get('X-Tag')).toEqual('child,root');
req.flush('');
});

it('should run root interceptors once in the parent request and response chain', () => {
const order: string[] = [];

TestBed.configureTestingModule({
providers: [
provideHttpClient(
...commonHttpFeatures,
withInterceptors([makeOrderedTagInterceptorFn('parent', order)]),
),
{
provide: HTTP_ROOT_INTERCEPTOR_FNS,
useValue: makeOrderedTagInterceptorFn('root', order),
multi: true,
},
provideHttpClientTesting(),
],
});

const child = createEnvironmentInjector(
[
provideHttpClient(
withRequestsMadeViaParent(),
withInterceptors([makeLiteralTagInterceptorFn('child')]),
withInterceptors([makeOrderedTagInterceptorFn('child', order)]),
),
],
TestBed.inject(EnvironmentInjector),
);

child.get(HttpClient).get('/test', {responseType: 'text'}).subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/test');
expect(req.request.headers.get('X-Tag')).toEqual('child,parent');
expect(req.request.headers.get('X-Tag')).toEqual('child,parent,root');
expect(order).toEqual(['child:request', 'parent:request', 'root:request']);
req.flush('');
expect(order).toEqual([
'child:request',
'parent:request',
'root:request',
'root:response',
'parent:response',
'child:response',
]);
});
});
}

it('should be able to connect to a legacy-provided HttpClient context', () => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [provideLegacyInterceptor('parent')],
});

const child = createEnvironmentInjector(
[
provideHttpClient(
withRequestsMadeViaParent(),
withInterceptors([makeLiteralTagInterceptorFn('child')]),
),
],
TestBed.inject(EnvironmentInjector),
);

child.get(HttpClient).get('/test', {responseType: 'text'}).subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/test');
expect(req.request.headers.get('X-Tag')).toEqual('child,parent');
req.flush('');
});

it('should inherit root interceptors in independent child contexts', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
{
provide: HTTP_ROOT_INTERCEPTOR_FNS,
useValue: makeLiteralTagInterceptorFn('root'),
multi: true,
},
provideHttpClientTesting(),
],
});

const delegatingParent = createEnvironmentInjector(
[provideHttpClient(withRequestsMadeViaParent())],
TestBed.inject(EnvironmentInjector),
);
const independentChild = createEnvironmentInjector(
[
provideHttpClient(withInterceptors([makeLiteralTagInterceptorFn('child')])),
{provide: HttpBackend, useValue: TestBed.inject(HttpBackend)},
],
delegatingParent,
);

try {
independentChild.get(HttpClient).get('/test', {responseType: 'text'}).subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/test');
expect(req.request.headers.get('X-Tag')).toEqual('child,root');
req.flush('');
} finally {
independentChild.destroy();
delegatingParent.destroy();
}
});

it('should inherit root interceptors when a custom provider overrides delegation', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
{
provide: HTTP_ROOT_INTERCEPTOR_FNS,
useValue: makeLiteralTagInterceptorFn('root'),
multi: true,
},
provideHttpClientTesting(),
],
});

const child = createEnvironmentInjector(
[
provideHttpClient(
withRequestsMadeViaParent(),
withInterceptors([makeLiteralTagInterceptorFn('child')]),
),
{provide: HttpBackend, useValue: TestBed.inject(HttpBackend)},
],
TestBed.inject(EnvironmentInjector),
);

try {
child.get(HttpClient).get('/test', {responseType: 'text'}).subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/test');
expect(req.request.headers.get('X-Tag')).toEqual('child,root');
req.flush('');
} finally {
child.destroy();
}
});
});

describe('compatibility with Http NgModules', () => {
Expand Down Expand Up @@ -653,6 +797,19 @@ function makeLiteralTagInterceptorFn(tag: string): HttpInterceptorFn {
return (req, next) => next(addTagToRequest(req, tag));
}

function makeOrderedTagInterceptorFn(tag: string, order: string[]): HttpInterceptorFn {
return (req, next) => {
order.push(`${tag}:request`);
return next(addTagToRequest(req, tag)).pipe(
tap((event) => {
if (event instanceof HttpResponse) {
order.push(`${tag}:response`);
}
}),
);
};
}

function makeTokenTagInterceptorFn(tag: InjectionToken<string>): HttpInterceptorFn {
return (req, next) => next(addTagToRequest(req, inject(tag)));
}
Expand Down
Loading
Loading