Explore all Angular open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Angular

bootstrap

4.6.1

angular

v14.0.0-next.14

TypeScript

TypeScript 4.7 Beta

storybook

ionic-framework

v6.1.3-nightly.20220422

Popular Libraries in Angular

bootstrap

by twbs doticonjavascriptdoticon

star image 156587 doticonMIT

The most popular HTML, CSS, and JavaScript framework for developing responsive, mobile first projects on the web.

angular

by angular doticontypescriptdoticon

star image 80840 doticonMIT

The modern web developer’s platform

TypeScript

by microsoft doticontypescriptdoticon

star image 79882 doticonApache-2.0

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

storybook

by storybookjs doticontypescriptdoticon

star image 70458 doticonMIT

📓 The UI component explorer. Develop, document, & test React, Vue, Angular, Web Components, Ember, Svelte & more!

angular.js

by angular doticonjavascriptdoticon

star image 59499 doticonMIT

AngularJS - HTML enhanced for web apps!

html5-boilerplate

by h5bp doticonjavascriptdoticon

star image 52642 doticonMIT

A professional front-end template for building fast, robust, and adaptable web apps or sites.

Semantic-UI

by Semantic-Org doticonjavascriptdoticon

star image 49510 doticonMIT

Semantic is a UI component framework based around useful principles from natural language.

ionic-framework

by ionic-team doticontypescriptdoticon

star image 46757 doticonNOASSERTION

A powerful cross-platform UI toolkit for building native-quality iOS, Android, and Progressive Web Apps with HTML, CSS, and JavaScript.

front-end-interview-handbook

by yangshun doticonjavascriptdoticon

star image 32705 doticonMIT

⚡️ Front End interview preparation materials for busy engineers

Trending New libraries in Angular

FE-Interview

by lgwebdream doticonjavascriptdoticon

star image 3960 doticonNOASSERTION

🔥🔥🔥 前端面试,独有前端面试题详解,前端面试刷题必备,1000+前端面试真题,Html、Css、JavaScript、Vue、React、Node、TypeScript、Webpack、算法、网络与安全、浏览器

keen-slider

by rcbyr doticontypescriptdoticon

star image 3299 doticonMIT

The touch slider carousel with the most native feeling

tsparticles

by matteobruni doticontypescriptdoticon

star image 3201 doticonMIT

tsParticles - Easily create highly customizable particles, confetti and fireworks animations and use them as animated backgrounds for your website. Ready to use components available for React.js, Vue.js (2.x and 3.x), Angular, Svelte, jQuery, Preact, Inferno, Solid, Riot and Web Components.

qwik

by BuilderIO doticontypescriptdoticon

star image 3098 doticonMIT

The HTML-first framework. Initialize apps of any size with < 1kb JS

goxygen

by Shpota doticongodoticon

star image 2353 doticonApache-2.0

Generate a modern Web project with Go and Angular, React or Vue in seconds 🚀

vime

by vime-js doticontypescriptdoticon

star image 2103 doticonMIT

Customizable, extensible, accessible and framework agnostic media player. Modern alternative to Video.js and Plyr. Supports HTML5, HLS, Dash, YouTube, Vimeo, Dailymotion...

taiga-ui

by TinkoffCreditSystems doticontypescriptdoticon

star image 1849 doticonApache-2.0

Angular UI Kit and components library for awesome people

sandpack

by codesandbox doticontypescriptdoticon

star image 1833 doticonApache-2.0

A component toolkit for creating live-running code editing experiences, using the power of CodeSandbox.

jira-clone-angular

by trungk18 doticontypescriptdoticon

star image 1724 doticon

A simplified Jira clone built with Angular, ng-zorro and Akita

Top Authors in Angular

1

PacktPublishing

107 Libraries

star icon1910

2

angular

98 Libraries

star icon268439

3

manfredsteyer

94 Libraries

star icon2560

4

didinj

69 Libraries

star icon1131

5

cornflourblue

60 Libraries

star icon4078

6

mgechev

57 Libraries

star icon11878

7

microsoft

53 Libraries

star icon95801

8

ionic-team

51 Libraries

star icon69625

9

SinghDigamber

48 Libraries

star icon805

10

PatrickJS

44 Libraries

star icon22825

1

107 Libraries

star icon1910

2

98 Libraries

star icon268439

3

94 Libraries

star icon2560

4

69 Libraries

star icon1131

5

60 Libraries

star icon4078

6

57 Libraries

star icon11878

7

53 Libraries

star icon95801

8

51 Libraries

star icon69625

9

48 Libraries

star icon805

10

44 Libraries

star icon22825

Trending Kits in Angular

No Trending Kits are available at this moment for Angular

Trending Discussions on Angular

AngularFireModule and AngularFireDatabaseModule not being found in @angular/fire

After upgrading from Angular 12 to 13, cache is too large for Github

In Angular Material what does setting up global typography styles mean?

angular 13 ng build library fails (ivy partial compilation mode)

throwError(error) is now deprecated, but there is no new Error(HttpErrorResponse)

My project doesn't compile with optimization parameters after upgrading from angular 11 to angular 12

Data path &quot;&quot; must NOT have additional properties(extractCss) in Angular 13 while upgrading project

What's the .angular directory in the project root about?

Angular 6 to 12 Migration: Getting Multiple Warning: Css Minimizer Plugin: &gt; Unexpected &quot;$&quot;

rxjs 7 update - Subject - Expected 1 arguments, but got 0

QUESTION

AngularFireModule and AngularFireDatabaseModule not being found in @angular/fire

Asked 2022-Apr-01 at 12:56

I am trying to implement Firebase Realtime Database into a angular project and Im getting stuck at one of the very first steps. Importing AngularFireModule and AngularFireDatabaseModule. It gives me the following error:

1Module '&quot;@angular/fire&quot;' has no exported member 'AngularFireModule'.ts(2305)
2
1Module '&quot;@angular/fire&quot;' has no exported member 'AngularFireModule'.ts(2305)
2Module '&quot;@angular/fire/database&quot;' has no exported member 'AngularFireDatabaseModule'.
3

And here is how I am importing them:

1Module '&quot;@angular/fire&quot;' has no exported member 'AngularFireModule'.ts(2305)
2Module '&quot;@angular/fire/database&quot;' has no exported member 'AngularFireDatabaseModule'.
3import {AngularFireModule } from '@angular/fire';
4import {AngularFireDatabaseModule} from '@angular/fire/database'
5

Am I missing something here? I have installed @angular/fire via the command

1Module '&quot;@angular/fire&quot;' has no exported member 'AngularFireModule'.ts(2305)
2Module '&quot;@angular/fire/database&quot;' has no exported member 'AngularFireDatabaseModule'.
3import {AngularFireModule } from '@angular/fire';
4import {AngularFireDatabaseModule} from '@angular/fire/database'
5npm i firebase @angular/fire
6

and have also installed firebase tools. Here is a list of the Angular packages I currently have installed and their versions:

1Module '&quot;@angular/fire&quot;' has no exported member 'AngularFireModule'.ts(2305)
2Module '&quot;@angular/fire/database&quot;' has no exported member 'AngularFireDatabaseModule'.
3import {AngularFireModule } from '@angular/fire';
4import {AngularFireDatabaseModule} from '@angular/fire/database'
5npm i firebase @angular/fire
6Angular CLI: 12.2.2
7Node: 14.17.4
8Package Manager: npm 6.14.14
9OS: win32 x64
10
11Angular: 12.2.3
12... animations, common, compiler, compiler-cli, core, forms
13... platform-browser, platform-browser-dynamic, router
14
15Package                         Version
16---------------------------------------------------------
17@angular-devkit/architect       0.1202.2
18@angular-devkit/build-angular   12.2.2
19@angular-devkit/core            12.2.2
20@angular-devkit/schematics      12.2.2
21@angular/cli                    12.2.2
22@angular/fire                   7.0.0
23@schematics/angular             12.2.2
24rxjs                            6.6.7
25typescript                      4.3.5
26

I do apologise if this is all excessive information but I am completely stuck as to what the issue is. Any help would be GREATLY appreciated. Right now my suspicion is that its a compatibility issue or perhaps a feature that doesnt exist anymore on the latest versions but I really dont know.

ANSWER

Answered 2021-Aug-26 at 13:20

AngularFire 7.0.0 was launched yesterday with a new API that has a lot of bundle size reduction benefits.

Instead of top level classes like AngularFireDatabase, you can now import smaller independent functions.

1Module '&quot;@angular/fire&quot;' has no exported member 'AngularFireModule'.ts(2305)
2Module '&quot;@angular/fire/database&quot;' has no exported member 'AngularFireDatabaseModule'.
3import {AngularFireModule } from '@angular/fire';
4import {AngularFireDatabaseModule} from '@angular/fire/database'
5npm i firebase @angular/fire
6Angular CLI: 12.2.2
7Node: 14.17.4
8Package Manager: npm 6.14.14
9OS: win32 x64
10
11Angular: 12.2.3
12... animations, common, compiler, compiler-cli, core, forms
13... platform-browser, platform-browser-dynamic, router
14
15Package                         Version
16---------------------------------------------------------
17@angular-devkit/architect       0.1202.2
18@angular-devkit/build-angular   12.2.2
19@angular-devkit/core            12.2.2
20@angular-devkit/schematics      12.2.2
21@angular/cli                    12.2.2
22@angular/fire                   7.0.0
23@schematics/angular             12.2.2
24rxjs                            6.6.7
25typescript                      4.3.5
26import { list } from '@angular/fire/database';
27

The initialization process is a bit different too as it has a more flexible API for specifying configurations.

1Module '&quot;@angular/fire&quot;' has no exported member 'AngularFireModule'.ts(2305)
2Module '&quot;@angular/fire/database&quot;' has no exported member 'AngularFireDatabaseModule'.
3import {AngularFireModule } from '@angular/fire';
4import {AngularFireDatabaseModule} from '@angular/fire/database'
5npm i firebase @angular/fire
6Angular CLI: 12.2.2
7Node: 14.17.4
8Package Manager: npm 6.14.14
9OS: win32 x64
10
11Angular: 12.2.3
12... animations, common, compiler, compiler-cli, core, forms
13... platform-browser, platform-browser-dynamic, router
14
15Package                         Version
16---------------------------------------------------------
17@angular-devkit/architect       0.1202.2
18@angular-devkit/build-angular   12.2.2
19@angular-devkit/core            12.2.2
20@angular-devkit/schematics      12.2.2
21@angular/cli                    12.2.2
22@angular/fire                   7.0.0
23@schematics/angular             12.2.2
24rxjs                            6.6.7
25typescript                      4.3.5
26import { list } from '@angular/fire/database';
27@NgModule({
28    imports: [
29        provideFirebaseApp(() =&gt; initializeApp(config)),
30        provideFirestore(() =&gt; {
31            const firestore = getFirestore();
32            connectEmulator(firestore, 'localhost', 8080);
33            enableIndexedDbPersistence(firestore);
34            return firestore;
35        }),
36        provideStorage(() =&gt; getStorage()),
37    ],
38})
39

If you want to proceed with the older API there's a compatibility layer.

1Module '&quot;@angular/fire&quot;' has no exported member 'AngularFireModule'.ts(2305)
2Module '&quot;@angular/fire/database&quot;' has no exported member 'AngularFireDatabaseModule'.
3import {AngularFireModule } from '@angular/fire';
4import {AngularFireDatabaseModule} from '@angular/fire/database'
5npm i firebase @angular/fire
6Angular CLI: 12.2.2
7Node: 14.17.4
8Package Manager: npm 6.14.14
9OS: win32 x64
10
11Angular: 12.2.3
12... animations, common, compiler, compiler-cli, core, forms
13... platform-browser, platform-browser-dynamic, router
14
15Package                         Version
16---------------------------------------------------------
17@angular-devkit/architect       0.1202.2
18@angular-devkit/build-angular   12.2.2
19@angular-devkit/core            12.2.2
20@angular-devkit/schematics      12.2.2
21@angular/cli                    12.2.2
22@angular/fire                   7.0.0
23@schematics/angular             12.2.2
24rxjs                            6.6.7
25typescript                      4.3.5
26import { list } from '@angular/fire/database';
27@NgModule({
28    imports: [
29        provideFirebaseApp(() =&gt; initializeApp(config)),
30        provideFirestore(() =&gt; {
31            const firestore = getFirestore();
32            connectEmulator(firestore, 'localhost', 8080);
33            enableIndexedDbPersistence(firestore);
34            return firestore;
35        }),
36        provideStorage(() =&gt; getStorage()),
37    ],
38})
39import { AngularFireModule} from '@angular/fire/compat'
40import { AngularFireDatabaseModule } from '@angular/fire/compat/database';
41

Source https://stackoverflow.com/questions/68939014

QUESTION

After upgrading from Angular 12 to 13, cache is too large for Github

Asked 2022-Mar-28 at 18:10

I recently upgraded all of my dependencies in package.json to the latest. I went from Angular 12.2.0 to 13.0.1 and github is now rejecting my push with the following file size error. Is there some setting I need to define in angular.json build profile that will help minimize these cache file sizes?

1remote: warning: File .angular/cache/angular-webpack/72163742903fc8ba00e684045de261c2e3a2fb86/3.pack is 54.01 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
2remote: warning: File .angular/cache/angular-webpack/72163742903fc8ba00e684045de261c2e3a2fb86/2.pack is 56.42 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
3remote: error: Trace: 0b9557fffbe30aac33f6d9858ef97559341c5c1614ace35524fcba85ac99ca76
4remote: error: See http://git.io/iEPt8g for more information.
5remote: error: File .angular/cache/angular-webpack/72163742903fc8ba00e684045de261c2e3a2fb86/3.pack is 122.06 MB; this exceeds GitHub's file size limit of 100.00 MB
6remote: error: File .angular/cache/angular-webpack/72163742903fc8ba00e684045de261c2e3a2fb86/5.pack is 123.92 MB; this exceeds GitHub's file size limit of 100.00 MB
7remote: error: File .angular/cache/angular-webpack/f48e9bc724ec0d5ae9a9d2fed858970d0a503f10/0.pack is 154.05 MB; this exceeds GitHub's file size limit of 100.00 MB
8remote: error: File .angular/cache/angular-webpack/9327900b3187f0b6351b4801d208e7b58f1af17e/0.pack is 165.50 MB; this exceeds GitHub's file size limit of 100.00 MB
9remote: error: File .angular/cache/angular-webpack/663bcd30d50863949acf1c25f02b95cab85c248a/0.pack is 151.56 MB; this exceeds GitHub's file size limit of 100.00 MB
10remote: error: File .angular/cache/angular-webpack/663bcd30d50863949acf1c25f02b95cab85c248a/0.pack is 151.55 MB; this exceeds GitHub's file size limit of 100.00 MB
11remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
12

Edit:

  1. I created this repo with Angular cli and have been maintaining and updating through many versions of Angular and had no issue until this latest update.

  2. The .gitignore file is in the root of the application and matches the suggested example: enter image description here

  3. When adding /.angular/cache to the gitignore file, I run git rm -rf --cached . && git add . && git commit -m 'fix(gitignore): add angular cache' && git push --set-upstream origin chore/bump-deps but still get the file size error.

ANSWER

Answered 2021-Nov-24 at 16:53

Make sure your .gitignore is in the parent folder of .angular.
In that .gitignore file, a simple .angular/cache/ should be enough to ignore that subfolder content.

Check it with:

1remote: warning: File .angular/cache/angular-webpack/72163742903fc8ba00e684045de261c2e3a2fb86/3.pack is 54.01 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
2remote: warning: File .angular/cache/angular-webpack/72163742903fc8ba00e684045de261c2e3a2fb86/2.pack is 56.42 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
3remote: error: Trace: 0b9557fffbe30aac33f6d9858ef97559341c5c1614ace35524fcba85ac99ca76
4remote: error: See http://git.io/iEPt8g for more information.
5remote: error: File .angular/cache/angular-webpack/72163742903fc8ba00e684045de261c2e3a2fb86/3.pack is 122.06 MB; this exceeds GitHub's file size limit of 100.00 MB
6remote: error: File .angular/cache/angular-webpack/72163742903fc8ba00e684045de261c2e3a2fb86/5.pack is 123.92 MB; this exceeds GitHub's file size limit of 100.00 MB
7remote: error: File .angular/cache/angular-webpack/f48e9bc724ec0d5ae9a9d2fed858970d0a503f10/0.pack is 154.05 MB; this exceeds GitHub's file size limit of 100.00 MB
8remote: error: File .angular/cache/angular-webpack/9327900b3187f0b6351b4801d208e7b58f1af17e/0.pack is 165.50 MB; this exceeds GitHub's file size limit of 100.00 MB
9remote: error: File .angular/cache/angular-webpack/663bcd30d50863949acf1c25f02b95cab85c248a/0.pack is 151.56 MB; this exceeds GitHub's file size limit of 100.00 MB
10remote: error: File .angular/cache/angular-webpack/663bcd30d50863949acf1c25f02b95cab85c248a/0.pack is 151.55 MB; this exceeds GitHub's file size limit of 100.00 MB
11remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
12git check-ignore -v -- .angular/cache/angular-webpack/72163742903fc8ba00e684045de261c2e3a2fb86/2.pack
13

You can see an example in ganatan/angular-starter/.gitignore (from an Angular 13 Example Starter project), where /.angular/cache/ is used, to anchor the rule to the top folder of the repository.

The OP S. Taylor confirms in the comments:

I'm pretty sure that was my issue.
I abandoned the dev branch and updated my dependencies without using the compound commands like git add . && git commit -m 'fix(gitignore): add angular cache'.
Making sure to note what was staged.

Source https://stackoverflow.com/questions/70088051

QUESTION

In Angular Material what does setting up global typography styles mean?

Asked 2022-Mar-16 at 01:12

When using ng add @angular/material to add Material support to an Angular project there is a prompt Set up global Angular Material typography styles?

What does this even mean? The documentation states the prompt appears, but does not describe what it actually means.

ANSWER

Answered 2022-Mar-16 at 01:12

By default, Angular Material doesn’t apply global CSS. Meaning that a standard element (eg. <h1>) will not have Angular materials' styles applied to it. So, when configured this way, in order to apply Angular material styles to a broad section of your HTML, you can use the mat-typography class

1&lt;h1&gt;This header doesn't have Angular Material styling&lt;/h1&gt;
2&lt;section class=&quot;mat-typography&quot;&gt;
3&lt;h1&gt;This header does have Angular Material styling&lt;/h1&gt;
4&lt;/section&gt;
5

If you set up global typography styles; then the first <h1> will already be styled.

Source https://stackoverflow.com/questions/69237215

QUESTION

angular 13 ng build library fails (ivy partial compilation mode)

Asked 2022-Mar-04 at 12:53

Recently I was having a problem installing an npm package (that used node-gyp). I tried upgrading the minor version of node from version 16.13.0 to 16.13.1 and upgrading my angular cli from 13.0.2 to 13.2.0. Once I got the package to install I generated a library with ng g library new-library. I don't know what what actually broke it, but now whenever I try to build alibrary it produces an error. I try ng build my-lib and get the below error.

1✖ Compiling with Angular sources in Ivy partial compilation mode.
2Transform failed with 1 error:
3error: Invalid version: &quot;15.2-15.3&quot;
4

I tried reverting the version of node and angular cli but it didn't fix the problem. I even reverted the code to its original state and I get the error now. Is this a problem with my environment? How do I fix this issue?

ANSWER

Answered 2022-Jan-30 at 07:21

This is a bug in Angular CLI 13.2.0.

Temporary solution:

Removing content configurating .browserslistrc file from root project. more info

Source https://stackoverflow.com/questions/70911458

QUESTION

throwError(error) is now deprecated, but there is no new Error(HttpErrorResponse)

Asked 2022-Mar-01 at 00:42

Apparently throwError(error) is now deprecated. The IntelliSense of VS Code suggests throwError(() => new Error('error'). new Error(...) accepts only strings. What's the correct way to replace it without breaking my HttpErrorHandlerService ?

http-error.interceptor.ts
1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent&lt;any&gt;) =&gt; this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) =&gt; this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest&lt;any&gt;): HttpRequest&lt;any&gt; {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent&lt;any&gt;): HttpEvent&lt;any&gt; {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest&lt;any&gt;,
46    next: HttpHandler
47  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse &amp;&amp; error.error &amp;&amp; error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150
auth.interceptor.ts
1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent&lt;any&gt;) =&gt; this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) =&gt; this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest&lt;any&gt;): HttpRequest&lt;any&gt; {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent&lt;any&gt;): HttpEvent&lt;any&gt; {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest&lt;any&gt;,
46    next: HttpHandler
47  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse &amp;&amp; error.error &amp;&amp; error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150import { Injectable } from '@angular/core';
151import {
152  HttpRequest,
153  HttpHandler,
154  HttpEvent,
155  HttpInterceptor,
156  HttpErrorResponse
157} from '@angular/common/http';
158import {
159  BehaviorSubject,
160  catchError,
161  EMPTY,
162  filter,
163  finalize,
164  Observable,
165  switchMap,
166  take,
167  throwError
168} from 'rxjs';
169
170import { AuthService } from '@core/services';
171import { AuthResponse } from '@core/types';
172
173@Injectable()
174export class AuthInterceptor implements HttpInterceptor {
175  private refreshTokenInProgress: boolean;
176  private refreshToken$ = new BehaviorSubject&lt;AuthResponse | null&gt;(null);
177
178  constructor(private authService: AuthService) {}
179
180  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
181    return next
182      .handle(this.performRequest(request))
183      .pipe(
184        catchError((error: HttpErrorResponse) =&gt; this.processRequestError(error, request, next))
185      );
186  }
187
188  private performRequest(request: HttpRequest&lt;any&gt;): HttpRequest&lt;any&gt; {
189    const accessToken = this.authService.getAccessToken();
190
191    let headers = request.headers;
192    if (accessToken) {
193      headers = headers.set('Authorization', `Bearer ${accessToken}`);
194    }
195
196    return request.clone({ headers });
197  }
198
199  private processRequestError(
200    error: HttpErrorResponse,
201    request: HttpRequest&lt;any&gt;,
202    next: HttpHandler
203  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
204    console.log('auth interceptor called');
205
206    if (
207      error instanceof HttpErrorResponse &amp;&amp;
208      error.status === 401 &amp;&amp;
209      this.authService.isSignedIn()
210    ) {
211      return this.refreshToken(request, next);
212    }
213
214    return throwError(error);
215  }
216
217  private refreshToken(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
218    console.log('refresh token in auth.interceptor called');
219
220    // in case the page consists of more than one requests
221    if (!this.refreshTokenInProgress) {
222      this.refreshToken$.next(null);
223      this.refreshTokenInProgress = true;
224
225      return this.authService.refreshToken().pipe(
226        switchMap((response) =&gt; {
227          if (response) {
228            this.refreshToken$.next(response);
229            return next.handle(this.performRequest(request));
230          }
231
232          this.authService.signOut();
233          return throwError(() =&gt; new Error(&quot;RefreshTokenFailed&quot;));
234        }),
235        catchError((error) =&gt; {
236          this.authService.signOut();
237          return throwError(error);
238        }),
239        finalize(() =&gt; (this.refreshTokenInProgress = false))
240      );
241    } else {
242      // wait while getting new token
243      return this.refreshToken$.pipe(
244        filter((result) =&gt; result !== null),
245        take(1),
246        switchMap(() =&gt; next.handle(this.performRequest(request)))
247      );
248    }
249  }
250}
251
252

ANSWER

Answered 2021-Aug-04 at 19:08

Instead of this:

1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent&lt;any&gt;) =&gt; this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) =&gt; this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest&lt;any&gt;): HttpRequest&lt;any&gt; {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent&lt;any&gt;): HttpEvent&lt;any&gt; {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest&lt;any&gt;,
46    next: HttpHandler
47  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse &amp;&amp; error.error &amp;&amp; error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150import { Injectable } from '@angular/core';
151import {
152  HttpRequest,
153  HttpHandler,
154  HttpEvent,
155  HttpInterceptor,
156  HttpErrorResponse
157} from '@angular/common/http';
158import {
159  BehaviorSubject,
160  catchError,
161  EMPTY,
162  filter,
163  finalize,
164  Observable,
165  switchMap,
166  take,
167  throwError
168} from 'rxjs';
169
170import { AuthService } from '@core/services';
171import { AuthResponse } from '@core/types';
172
173@Injectable()
174export class AuthInterceptor implements HttpInterceptor {
175  private refreshTokenInProgress: boolean;
176  private refreshToken$ = new BehaviorSubject&lt;AuthResponse | null&gt;(null);
177
178  constructor(private authService: AuthService) {}
179
180  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
181    return next
182      .handle(this.performRequest(request))
183      .pipe(
184        catchError((error: HttpErrorResponse) =&gt; this.processRequestError(error, request, next))
185      );
186  }
187
188  private performRequest(request: HttpRequest&lt;any&gt;): HttpRequest&lt;any&gt; {
189    const accessToken = this.authService.getAccessToken();
190
191    let headers = request.headers;
192    if (accessToken) {
193      headers = headers.set('Authorization', `Bearer ${accessToken}`);
194    }
195
196    return request.clone({ headers });
197  }
198
199  private processRequestError(
200    error: HttpErrorResponse,
201    request: HttpRequest&lt;any&gt;,
202    next: HttpHandler
203  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
204    console.log('auth interceptor called');
205
206    if (
207      error instanceof HttpErrorResponse &amp;&amp;
208      error.status === 401 &amp;&amp;
209      this.authService.isSignedIn()
210    ) {
211      return this.refreshToken(request, next);
212    }
213
214    return throwError(error);
215  }
216
217  private refreshToken(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
218    console.log('refresh token in auth.interceptor called');
219
220    // in case the page consists of more than one requests
221    if (!this.refreshTokenInProgress) {
222      this.refreshToken$.next(null);
223      this.refreshTokenInProgress = true;
224
225      return this.authService.refreshToken().pipe(
226        switchMap((response) =&gt; {
227          if (response) {
228            this.refreshToken$.next(response);
229            return next.handle(this.performRequest(request));
230          }
231
232          this.authService.signOut();
233          return throwError(() =&gt; new Error(&quot;RefreshTokenFailed&quot;));
234        }),
235        catchError((error) =&gt; {
236          this.authService.signOut();
237          return throwError(error);
238        }),
239        finalize(() =&gt; (this.refreshTokenInProgress = false))
240      );
241    } else {
242      // wait while getting new token
243      return this.refreshToken$.pipe(
244        filter((result) =&gt; result !== null),
245        take(1),
246        switchMap(() =&gt; next.handle(this.performRequest(request)))
247      );
248    }
249  }
250}
251
252    catchError((error) =&gt; {
253      this.authService.signOut();
254      return throwError(error);
255    }),
256

You could try this:

1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent&lt;any&gt;) =&gt; this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) =&gt; this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest&lt;any&gt;): HttpRequest&lt;any&gt; {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent&lt;any&gt;): HttpEvent&lt;any&gt; {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest&lt;any&gt;,
46    next: HttpHandler
47  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse &amp;&amp; error.error &amp;&amp; error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150import { Injectable } from '@angular/core';
151import {
152  HttpRequest,
153  HttpHandler,
154  HttpEvent,
155  HttpInterceptor,
156  HttpErrorResponse
157} from '@angular/common/http';
158import {
159  BehaviorSubject,
160  catchError,
161  EMPTY,
162  filter,
163  finalize,
164  Observable,
165  switchMap,
166  take,
167  throwError
168} from 'rxjs';
169
170import { AuthService } from '@core/services';
171import { AuthResponse } from '@core/types';
172
173@Injectable()
174export class AuthInterceptor implements HttpInterceptor {
175  private refreshTokenInProgress: boolean;
176  private refreshToken$ = new BehaviorSubject&lt;AuthResponse | null&gt;(null);
177
178  constructor(private authService: AuthService) {}
179
180  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
181    return next
182      .handle(this.performRequest(request))
183      .pipe(
184        catchError((error: HttpErrorResponse) =&gt; this.processRequestError(error, request, next))
185      );
186  }
187
188  private performRequest(request: HttpRequest&lt;any&gt;): HttpRequest&lt;any&gt; {
189    const accessToken = this.authService.getAccessToken();
190
191    let headers = request.headers;
192    if (accessToken) {
193      headers = headers.set('Authorization', `Bearer ${accessToken}`);
194    }
195
196    return request.clone({ headers });
197  }
198
199  private processRequestError(
200    error: HttpErrorResponse,
201    request: HttpRequest&lt;any&gt;,
202    next: HttpHandler
203  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
204    console.log('auth interceptor called');
205
206    if (
207      error instanceof HttpErrorResponse &amp;&amp;
208      error.status === 401 &amp;&amp;
209      this.authService.isSignedIn()
210    ) {
211      return this.refreshToken(request, next);
212    }
213
214    return throwError(error);
215  }
216
217  private refreshToken(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
218    console.log('refresh token in auth.interceptor called');
219
220    // in case the page consists of more than one requests
221    if (!this.refreshTokenInProgress) {
222      this.refreshToken$.next(null);
223      this.refreshTokenInProgress = true;
224
225      return this.authService.refreshToken().pipe(
226        switchMap((response) =&gt; {
227          if (response) {
228            this.refreshToken$.next(response);
229            return next.handle(this.performRequest(request));
230          }
231
232          this.authService.signOut();
233          return throwError(() =&gt; new Error(&quot;RefreshTokenFailed&quot;));
234        }),
235        catchError((error) =&gt; {
236          this.authService.signOut();
237          return throwError(error);
238        }),
239        finalize(() =&gt; (this.refreshTokenInProgress = false))
240      );
241    } else {
242      // wait while getting new token
243      return this.refreshToken$.pipe(
244        filter((result) =&gt; result !== null),
245        take(1),
246        switchMap(() =&gt; next.handle(this.performRequest(request)))
247      );
248    }
249  }
250}
251
252    catchError((error) =&gt; {
253      this.authService.signOut();
254      return throwError(error);
255    }),
256    catchError((error) =&gt; {
257      this.authService.signOut();
258      return throwError(() =&gt; error);
259    }),
260

I wasn't able to test it thoroughly, but a simple attempt seemed to work.

This was my simple test (using RxJS v7.2):

Service

1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent&lt;any&gt;) =&gt; this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) =&gt; this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest&lt;any&gt;): HttpRequest&lt;any&gt; {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent&lt;any&gt;): HttpEvent&lt;any&gt; {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest&lt;any&gt;,
46    next: HttpHandler
47  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse &amp;&amp; error.error &amp;&amp; error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150import { Injectable } from '@angular/core';
151import {
152  HttpRequest,
153  HttpHandler,
154  HttpEvent,
155  HttpInterceptor,
156  HttpErrorResponse
157} from '@angular/common/http';
158import {
159  BehaviorSubject,
160  catchError,
161  EMPTY,
162  filter,
163  finalize,
164  Observable,
165  switchMap,
166  take,
167  throwError
168} from 'rxjs';
169
170import { AuthService } from '@core/services';
171import { AuthResponse } from '@core/types';
172
173@Injectable()
174export class AuthInterceptor implements HttpInterceptor {
175  private refreshTokenInProgress: boolean;
176  private refreshToken$ = new BehaviorSubject&lt;AuthResponse | null&gt;(null);
177
178  constructor(private authService: AuthService) {}
179
180  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
181    return next
182      .handle(this.performRequest(request))
183      .pipe(
184        catchError((error: HttpErrorResponse) =&gt; this.processRequestError(error, request, next))
185      );
186  }
187
188  private performRequest(request: HttpRequest&lt;any&gt;): HttpRequest&lt;any&gt; {
189    const accessToken = this.authService.getAccessToken();
190
191    let headers = request.headers;
192    if (accessToken) {
193      headers = headers.set('Authorization', `Bearer ${accessToken}`);
194    }
195
196    return request.clone({ headers });
197  }
198
199  private processRequestError(
200    error: HttpErrorResponse,
201    request: HttpRequest&lt;any&gt;,
202    next: HttpHandler
203  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
204    console.log('auth interceptor called');
205
206    if (
207      error instanceof HttpErrorResponse &amp;&amp;
208      error.status === 401 &amp;&amp;
209      this.authService.isSignedIn()
210    ) {
211      return this.refreshToken(request, next);
212    }
213
214    return throwError(error);
215  }
216
217  private refreshToken(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
218    console.log('refresh token in auth.interceptor called');
219
220    // in case the page consists of more than one requests
221    if (!this.refreshTokenInProgress) {
222      this.refreshToken$.next(null);
223      this.refreshTokenInProgress = true;
224
225      return this.authService.refreshToken().pipe(
226        switchMap((response) =&gt; {
227          if (response) {
228            this.refreshToken$.next(response);
229            return next.handle(this.performRequest(request));
230          }
231
232          this.authService.signOut();
233          return throwError(() =&gt; new Error(&quot;RefreshTokenFailed&quot;));
234        }),
235        catchError((error) =&gt; {
236          this.authService.signOut();
237          return throwError(error);
238        }),
239        finalize(() =&gt; (this.refreshTokenInProgress = false))
240      );
241    } else {
242      // wait while getting new token
243      return this.refreshToken$.pipe(
244        filter((result) =&gt; result !== null),
245        take(1),
246        switchMap(() =&gt; next.handle(this.performRequest(request)))
247      );
248    }
249  }
250}
251
252    catchError((error) =&gt; {
253      this.authService.signOut();
254      return throwError(error);
255    }),
256    catchError((error) =&gt; {
257      this.authService.signOut();
258      return throwError(() =&gt; error);
259    }),
260  getProducts(): Observable&lt;IProduct[]&gt; {
261    return this.http.get&lt;IProduct[]&gt;(this.productUrl)
262      .pipe(
263        tap(data =&gt; console.log('All: ', JSON.stringify(data))),
264        catchError(this.handleError)
265      );
266  }
267
268  private handleError(err: HttpErrorResponse): Observable&lt;never&gt; {
269    // just a test ... more could would go here
270    return throwError(() =&gt; err);
271  }
272

Notice that err here is of type HttpErrorResponse.

Component

1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent&lt;any&gt;) =&gt; this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) =&gt; this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest&lt;any&gt;): HttpRequest&lt;any&gt; {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent&lt;any&gt;): HttpEvent&lt;any&gt; {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest&lt;any&gt;,
46    next: HttpHandler
47  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse &amp;&amp; error.error &amp;&amp; error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150import { Injectable } from '@angular/core';
151import {
152  HttpRequest,
153  HttpHandler,
154  HttpEvent,
155  HttpInterceptor,
156  HttpErrorResponse
157} from '@angular/common/http';
158import {
159  BehaviorSubject,
160  catchError,
161  EMPTY,
162  filter,
163  finalize,
164  Observable,
165  switchMap,
166  take,
167  throwError
168} from 'rxjs';
169
170import { AuthService } from '@core/services';
171import { AuthResponse } from '@core/types';
172
173@Injectable()
174export class AuthInterceptor implements HttpInterceptor {
175  private refreshTokenInProgress: boolean;
176  private refreshToken$ = new BehaviorSubject&lt;AuthResponse | null&gt;(null);
177
178  constructor(private authService: AuthService) {}
179
180  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
181    return next
182      .handle(this.performRequest(request))
183      .pipe(
184        catchError((error: HttpErrorResponse) =&gt; this.processRequestError(error, request, next))
185      );
186  }
187
188  private performRequest(request: HttpRequest&lt;any&gt;): HttpRequest&lt;any&gt; {
189    const accessToken = this.authService.getAccessToken();
190
191    let headers = request.headers;
192    if (accessToken) {
193      headers = headers.set('Authorization', `Bearer ${accessToken}`);
194    }
195
196    return request.clone({ headers });
197  }
198
199  private processRequestError(
200    error: HttpErrorResponse,
201    request: HttpRequest&lt;any&gt;,
202    next: HttpHandler
203  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
204    console.log('auth interceptor called');
205
206    if (
207      error instanceof HttpErrorResponse &amp;&amp;
208      error.status === 401 &amp;&amp;
209      this.authService.isSignedIn()
210    ) {
211      return this.refreshToken(request, next);
212    }
213
214    return throwError(error);
215  }
216
217  private refreshToken(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
218    console.log('refresh token in auth.interceptor called');
219
220    // in case the page consists of more than one requests
221    if (!this.refreshTokenInProgress) {
222      this.refreshToken$.next(null);
223      this.refreshTokenInProgress = true;
224
225      return this.authService.refreshToken().pipe(
226        switchMap((response) =&gt; {
227          if (response) {
228            this.refreshToken$.next(response);
229            return next.handle(this.performRequest(request));
230          }
231
232          this.authService.signOut();
233          return throwError(() =&gt; new Error(&quot;RefreshTokenFailed&quot;));
234        }),
235        catchError((error) =&gt; {
236          this.authService.signOut();
237          return throwError(error);
238        }),
239        finalize(() =&gt; (this.refreshTokenInProgress = false))
240      );
241    } else {
242      // wait while getting new token
243      return this.refreshToken$.pipe(
244        filter((result) =&gt; result !== null),
245        take(1),
246        switchMap(() =&gt; next.handle(this.performRequest(request)))
247      );
248    }
249  }
250}
251
252    catchError((error) =&gt; {
253      this.authService.signOut();
254      return throwError(error);
255    }),
256    catchError((error) =&gt; {
257      this.authService.signOut();
258      return throwError(() =&gt; error);
259    }),
260  getProducts(): Observable&lt;IProduct[]&gt; {
261    return this.http.get&lt;IProduct[]&gt;(this.productUrl)
262      .pipe(
263        tap(data =&gt; console.log('All: ', JSON.stringify(data))),
264        catchError(this.handleError)
265      );
266  }
267
268  private handleError(err: HttpErrorResponse): Observable&lt;never&gt; {
269    // just a test ... more could would go here
270    return throwError(() =&gt; err);
271  }
272  ngOnInit(): void {
273    this.sub = this.productService.getProducts().subscribe({
274      next: products =&gt; {
275        this.products = products;
276        this.filteredProducts = this.products;
277      },
278      error: err =&gt; this.errorMessage = err.message
279    });
280  }
281

Here I was able to retrieve the message property from the error response and display it in my UI.

Let me know if this works for you.

Source https://stackoverflow.com/questions/68655492

QUESTION

My project doesn't compile with optimization parameters after upgrading from angular 11 to angular 12

Asked 2022-Jan-31 at 19:50

I just upgraded an environment with nrwl from angular version 11 to 12 with two angular applications and several libraries. After update when I try to compile using optimization settings:

angular.json

1{
2 ....
3 &quot;optimization&quot;: {
4    &quot;scripts&quot;: true,
5    &quot;styles&quot;: {
6       &quot;minify&quot;: true,
7       &quot;inlineCritical&quot;: false
8     },
9     &quot;fonts&quot;: true
10  },
11}
12

It gives me the following error (sass and scss component files):

1{
2 ....
3 &quot;optimization&quot;: {
4    &quot;scripts&quot;: true,
5    &quot;styles&quot;: {
6       &quot;minify&quot;: true,
7       &quot;inlineCritical&quot;: false
8     },
9     &quot;fonts&quot;: true
10  },
11}
12/home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/libs/ui-share-components/src/lib/top-panel/top-panel/top-panel.component.sass - Error: /home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/libs/ui-share-components/src/lib/top-panel/top-panel/top-panel.component.sass from Css Minimizer
13Error: Transform failed with 1 error:
14error: Invalid version: &quot;15.2-15.3&quot;
15    at failureErrorWithLog (/home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:1493:15)
16    at /home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:1282:29
17    at /home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:629:9
18    at handleIncomingPacket (/home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:726:9)
19    at Socket.readFromStdout (/home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:596:7)
20    at Socket.emit (events.js:315:20)
21    at addChunk (_stream_readable.js:309:12)
22    at readableAddChunk (_stream_readable.js:284:9)
23    at Socket.Readable.push (_stream_readable.js:223:10)
24    at Pipe.onStreamRead (internal/stream_base_commons.js:188:23)
25

Disabling styles.minify and fonts compiles without problems:

1{
2 ....
3 &quot;optimization&quot;: {
4    &quot;scripts&quot;: true,
5    &quot;styles&quot;: {
6       &quot;minify&quot;: true,
7       &quot;inlineCritical&quot;: false
8     },
9     &quot;fonts&quot;: true
10  },
11}
12/home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/libs/ui-share-components/src/lib/top-panel/top-panel/top-panel.component.sass - Error: /home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/libs/ui-share-components/src/lib/top-panel/top-panel/top-panel.component.sass from Css Minimizer
13Error: Transform failed with 1 error:
14error: Invalid version: &quot;15.2-15.3&quot;
15    at failureErrorWithLog (/home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:1493:15)
16    at /home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:1282:29
17    at /home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:629:9
18    at handleIncomingPacket (/home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:726:9)
19    at Socket.readFromStdout (/home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:596:7)
20    at Socket.emit (events.js:315:20)
21    at addChunk (_stream_readable.js:309:12)
22    at readableAddChunk (_stream_readable.js:284:9)
23    at Socket.Readable.push (_stream_readable.js:223:10)
24    at Pipe.onStreamRead (internal/stream_base_commons.js:188:23)
25&quot;optimization&quot;: {
26    &quot;scripts&quot;: true,
27    &quot;styles&quot;: {
28       &quot;minify&quot;: false,
29       &quot;inlineCritical&quot;: false
30     },
31     &quot;fonts&quot;: false
32  },
33}
34

ANSWER

Answered 2022-Jan-31 at 19:50

Reason of the issue

It is expected browserslist to return an entry for each version ("safari 15.2", "safari 15.3") instead of a range ("safari 15.2-15.3"). So, this is just a bug in the parsing logic of Safari browser versions which needs to be corrected and will be done soon in fixed versions of Angular 12/Angular 13. Link to details is here.

IMPORTANT UPDATE:

This is fixed in v12.2.16 and v13.2.1, please update if you are experiencing this issue. Users on v11 shouldn't be affected. Link to details is here. If you can not/do not want to update for any reason, then one of the workarounds below can be used.

Workarounds:

Modify .browserslistrc

Add to .browserslistrc such lines:

1{
2 ....
3 &quot;optimization&quot;: {
4    &quot;scripts&quot;: true,
5    &quot;styles&quot;: {
6       &quot;minify&quot;: true,
7       &quot;inlineCritical&quot;: false
8     },
9     &quot;fonts&quot;: true
10  },
11}
12/home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/libs/ui-share-components/src/lib/top-panel/top-panel/top-panel.component.sass - Error: /home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/libs/ui-share-components/src/lib/top-panel/top-panel/top-panel.component.sass from Css Minimizer
13Error: Transform failed with 1 error:
14error: Invalid version: &quot;15.2-15.3&quot;
15    at failureErrorWithLog (/home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:1493:15)
16    at /home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:1282:29
17    at /home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:629:9
18    at handleIncomingPacket (/home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:726:9)
19    at Socket.readFromStdout (/home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:596:7)
20    at Socket.emit (events.js:315:20)
21    at addChunk (_stream_readable.js:309:12)
22    at readableAddChunk (_stream_readable.js:284:9)
23    at Socket.Readable.push (_stream_readable.js:223:10)
24    at Pipe.onStreamRead (internal/stream_base_commons.js:188:23)
25&quot;optimization&quot;: {
26    &quot;scripts&quot;: true,
27    &quot;styles&quot;: {
28       &quot;minify&quot;: false,
29       &quot;inlineCritical&quot;: false
30     },
31     &quot;fonts&quot;: false
32  },
33}
34not ios_saf 15.2-15.3 # temporary solution to avoid build issues https://github.com/nrwl/nx/issues/8768
35not safari 15.2-15.3  # temporary solution to avoid build issues https://github.com/nrwl/nx/issues/8768
36

It has to come AFTER any mentions of ios_saf or safari. Otherwise, it doesn't work. Link to workaround is here.

Erase content of .browserslistrc

Erasing content of .browserslistrc helps to fix builds. Link to workaround is here.

Delete .browserslistrc

Deletion of .browserslistrc helps to fix builds. Link to workaround is here.

Install caniuse-lite

Add caniuse-lite package:

1{
2 ....
3 &quot;optimization&quot;: {
4    &quot;scripts&quot;: true,
5    &quot;styles&quot;: {
6       &quot;minify&quot;: true,
7       &quot;inlineCritical&quot;: false
8     },
9     &quot;fonts&quot;: true
10  },
11}
12/home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/libs/ui-share-components/src/lib/top-panel/top-panel/top-panel.component.sass - Error: /home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/libs/ui-share-components/src/lib/top-panel/top-panel/top-panel.component.sass from Css Minimizer
13Error: Transform failed with 1 error:
14error: Invalid version: &quot;15.2-15.3&quot;
15    at failureErrorWithLog (/home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:1493:15)
16    at /home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:1282:29
17    at /home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:629:9
18    at handleIncomingPacket (/home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:726:9)
19    at Socket.readFromStdout (/home/jose/WORK/Rental/REAL/APPS/angular-nx-ws/node_modules/@angular-devkit/build-angular/node_modules/esbuild/lib/main.js:596:7)
20    at Socket.emit (events.js:315:20)
21    at addChunk (_stream_readable.js:309:12)
22    at readableAddChunk (_stream_readable.js:284:9)
23    at Socket.Readable.push (_stream_readable.js:223:10)
24    at Pipe.onStreamRead (internal/stream_base_commons.js:188:23)
25&quot;optimization&quot;: {
26    &quot;scripts&quot;: true,
27    &quot;styles&quot;: {
28       &quot;minify&quot;: false,
29       &quot;inlineCritical&quot;: false
30     },
31     &quot;fonts&quot;: false
32  },
33}
34not ios_saf 15.2-15.3 # temporary solution to avoid build issues https://github.com/nrwl/nx/issues/8768
35not safari 15.2-15.3  # temporary solution to avoid build issues https://github.com/nrwl/nx/issues/8768
36npm install caniuse-lite@1.0.30001303 --save-dev --save-exact
37

Link to workaround is here.

Source https://stackoverflow.com/questions/70910612

QUESTION

Data path &quot;&quot; must NOT have additional properties(extractCss) in Angular 13 while upgrading project

Asked 2022-Jan-27 at 14:41

I am facing an issue while upgrading my project from angular 8.2.1 to angular 13 version.

After a successful upgrade while preparing a build it is giving me the following error.

1Data path &quot;&quot; must NOT have additional properties(extractCss).
2

I already renamed styleext with style in the angular.json file, but still not able to find the root cause for this error.

angular.json file is as follows.

1Data path &quot;&quot; must NOT have additional properties(extractCss).
2  {
3  &quot;$schema&quot;: &quot;./node_modules/@angular/cli/lib/config/schema.json&quot;,
4  &quot;version&quot;: 1,
5  &quot;newProjectRoot&quot;: &quot;projects&quot;,
6  &quot;projects&quot;: {
7    &quot;qiwkCollaborator&quot;: {
8      &quot;projectType&quot;: &quot;application&quot;,
9      &quot;schematics&quot;: {
10        &quot;@schematics/angular:component&quot;: {
11          &quot;style&quot;: &quot;scss&quot;
12        }
13      },
14      &quot;root&quot;: &quot;&quot;,
15      &quot;sourceRoot&quot;: &quot;src&quot;,
16      &quot;prefix&quot;: &quot;app&quot;,
17      &quot;architect&quot;: {
18        &quot;build&quot;: {
19
20        /*  &quot;configurations&quot;: {
21            &quot;fr&quot;: {
22            &quot;aot&quot;: true,
23            &quot;outputPath&quot;: &quot;dist/qwikCollaborator/fr/&quot;,
24            &quot;i18nFile&quot;: &quot;src/translate/messages.fr.xlf&quot;,      
25            &quot;i18nFormat&quot;: &quot;xlf&quot;,      
26            &quot;i18nLocale&quot;: &quot;fr&quot;,      
27            &quot;i18nMissingTranslation&quot;: &quot;error&quot;    
28             },
29             &quot;en&quot;: {
30            &quot;aot&quot;: true,
31            &quot;outputPath&quot;: &quot;dist/qwikCollaborator/en/&quot;,
32            &quot;i18nFile&quot;: &quot;src/translate/messages.en.xlf&quot;,      
33            &quot;i18nFormat&quot;: &quot;xlf&quot;,      
34            &quot;i18nLocale&quot;: &quot;en&quot;,      
35            &quot;i18nMissingTranslation&quot;: &quot;error&quot;    
36             }  
37           },*/
38          &quot;builder&quot;: &quot;@angular-devkit/build-angular:browser&quot;,
39          &quot;options&quot;: {
40            &quot;outputPath&quot;: &quot;dist/qiwkCollaborator&quot;,
41            &quot;index&quot;: &quot;src/index.html&quot;,
42            &quot;main&quot;: &quot;src/main.ts&quot;,
43            &quot;polyfills&quot;: &quot;src/polyfills.ts&quot;,
44            &quot;tsConfig&quot;: &quot;tsconfig.app.json&quot;,
45            &quot;aot&quot;: false,
46            &quot;assets&quot;: [
47              &quot;src/favicon.ico&quot;,
48              &quot;src/assets&quot;
49            ],
50            &quot;styles&quot;: [
51              &quot;src/styles.scss&quot;,
52              &quot;src/assets/css/custom-mobile.css&quot;,
53              &quot;src/assets/css/custom.css&quot;
54            ],
55            &quot;scripts&quot;: [
56              &quot;node_modules/jquery/dist/jquery.min.js&quot;,
57              &quot;src/assets/js/qwikCollaborator.js&quot;
58            ]
59          },
60          &quot;configurations&quot;: {
61          &quot;es5&quot;: {
62        &quot;tsConfig&quot;: &quot;./tsconfig.es5.json&quot;
63      },
64            &quot;production&quot;: {
65              &quot;fileReplacements&quot;: [
66                {
67                  &quot;replace&quot;: &quot;src/environments/environment.ts&quot;,
68                  &quot;with&quot;: &quot;src/environments/environment.prod.ts&quot;
69                }
70              ],
71              &quot;optimization&quot;: true,
72              &quot;outputHashing&quot;: &quot;all&quot;,
73              &quot;sourceMap&quot;: false,
74              &quot;extractCss&quot;: true,
75              &quot;namedChunks&quot;: false,
76              &quot;aot&quot;: true,
77              &quot;extractLicenses&quot;: true,
78              &quot;vendorChunk&quot;: false,
79              &quot;buildOptimizer&quot;: true,
80              &quot;budgets&quot;: [
81                {
82                  &quot;type&quot;: &quot;initial&quot;,
83                  &quot;maximumWarning&quot;: &quot;2mb&quot;,
84                  &quot;maximumError&quot;: &quot;5mb&quot;
85                },
86                {
87                  &quot;type&quot;: &quot;anyComponentStyle&quot;,
88                  &quot;maximumWarning&quot;: &quot;6kb&quot;,
89                  &quot;maximumError&quot;: &quot;10kb&quot;
90                }
91              ]
92            }
93          }
94        },
95        &quot;serve&quot;: {
96         /*  &quot;configurations&quot;: {
97            &quot;fr&quot;: {
98            &quot;browserTarget&quot;: &quot;qwikCollaborator:build:fr&quot; 
99            },
100            &quot;en&quot;: {
101            &quot;browserTarget&quot;: &quot;qwikCollaborator:build:en&quot; 
102            } ,
103            },*/
104          &quot;builder&quot;: &quot;@angular-devkit/build-angular:dev-server&quot;,
105          &quot;options&quot;: {
106            &quot;browserTarget&quot;: &quot;qiwkCollaborator:build&quot;
107          },
108         
109          &quot;configurations&quot;: {
110          &quot;es5&quot;: {
111        &quot;browserTarget&quot;: &quot;qiwkCollaborator:build:es5&quot;
112      },
113            &quot;production&quot;: {
114              &quot;browserTarget&quot;: &quot;qiwkCollaborator:build:es5&quot;
115            }
116          }
117        },
118        &quot;extract-i18n&quot;: {
119          &quot;builder&quot;: &quot;@angular-devkit/build-angular:extract-i18n&quot;,
120          &quot;options&quot;: {
121            &quot;browserTarget&quot;: &quot;qiwkCollaborator:build&quot;
122          }
123        },
124        &quot;test&quot;: {
125          &quot;builder&quot;: &quot;@angular-devkit/build-angular:karma&quot;,
126          &quot;options&quot;: {
127            &quot;main&quot;: &quot;src/test.ts&quot;,
128            &quot;polyfills&quot;: &quot;src/polyfills.ts&quot;,
129            &quot;tsConfig&quot;: &quot;tsconfig.spec.json&quot;,
130            &quot;karmaConfig&quot;: &quot;karma.conf.js&quot;,
131            &quot;assets&quot;: [
132              &quot;src/favicon.ico&quot;,
133              &quot;src/assets&quot;
134            ],
135            &quot;styles&quot;: [
136              &quot;src/styles.scss&quot;
137            ],
138            &quot;scripts&quot;: [&quot;../node_modules/jspdf/dist/jspdf.min.js&quot;]
139          }
140        },
141        &quot;lint&quot;: {
142          &quot;builder&quot;: &quot;@angular-devkit/build-angular:tslint&quot;,
143          &quot;options&quot;: {
144            &quot;tsConfig&quot;: [
145              &quot;tsconfig.app.json&quot;,
146              &quot;tsconfig.spec.json&quot;,
147              &quot;e2e/tsconfig.json&quot;
148            ],
149            &quot;exclude&quot;: [
150              &quot;**/node_modules/**&quot;
151            ]
152          }
153        },
154        &quot;e2e&quot;: {
155          &quot;builder&quot;: &quot;@angular-devkit/build-angular:protractor&quot;,
156          &quot;options&quot;: {
157            &quot;protractorConfig&quot;: &quot;e2e/protractor.conf.js&quot;,
158            &quot;devServerTarget&quot;: &quot;qiwkCollaborator:serve&quot;
159          },
160          &quot;configurations&quot;: {
161            &quot;production&quot;: {
162              &quot;devServerTarget&quot;: &quot;qiwkCollaborator:serve:production&quot;
163            }
164          }
165        }
166      }
167    }},
168  &quot;defaultProject&quot;: &quot;qiwkCollaborator&quot;
169}
170

How to get rid of this additional property?

can anyone help me with this?

thanks in advance!

ANSWER

Answered 2021-Dec-14 at 12:45

Just remove the "extractCss": true from your production environment, it will resolve the problem.

The reason about it is extractCss is deprecated, and it's value is true by default. See more here: Extracting CSS into JS with Angular 11 (deprecated extractCss)

Source https://stackoverflow.com/questions/70344098

QUESTION

What's the .angular directory in the project root about?

Asked 2021-Dec-02 at 10:07

According to the docs, there's nothing called .angular being regarded. Yet, in my project, I get that directory, immediately in the root of the project (on the same level as e.g. package.json).

It wasn't there before because my .gitignore would've barked at it. Currently, I'm trying out the latest Angular version, 13.0 and I conclude that it's a new addition to the tooling. Probably, it's some temporary stuff, since its contents are the following.

  • .angular/cache/angular-webpack
  • .angular/cache/babel-webpack

It was pointless to google .angular directory dot what is and the only (semi-)relevant hit I got was the docs linked above.

What's up with .angular directory and do I need to care (and/or version control it)?

ANSWER

Answered 2021-Dec-02 at 10:07

".angular/cache" folder should be ignored by your version control system (git, svn etc...)

Example for git, add this line to .gitignore file

1.angular/cache
2

(source : ng new command with @angular/cli v13)

Source https://stackoverflow.com/questions/70069852

QUESTION

Angular 6 to 12 Migration: Getting Multiple Warning: Css Minimizer Plugin: &gt; Unexpected &quot;$&quot;

Asked 2021-Nov-19 at 17:27

After migrating my angular 6 project to 12. I am getting multiple warning in terminal

if in angular.json i set optimisation: false configuration then all issue get resolved but i don't want to make this changes it should be true only.

with optimisation: true i am getting all these warnings:-

Earlier same code was working fine without any warning.

1assets/.../variables.scss - Warning: Css Minimizer Plugin:  &gt; assets/.../variables.scss:6:0: warning: Unexpected &quot;$&quot;
2    6 │ $color-normal-gray:#8a8a8a;
3      ╵ ^
4
5assets/.../global.scss - Warning: Css Minimizer Plugin:  &gt; 
6assets/.../global.scss:285:2: warning: Expected identifier but found &quot;.&quot;
7    285 │   .dropdown-menu{
8        ╵   ^
9
10assets/.../global.scss - Warning: Css Minimizer Plugin:  &gt; 
11assets/.../global.scss:255:6: warning: Expected identifier but found &quot;*&quot;
12    255 │       *background-color: #d9d9d9;
13        ╵       ^
14
15assets/.../master.scss - Warning: Css Minimizer Plugin:  &gt; 
16assets/.../master.scss:567:8: warning: Expected &quot;:&quot; but found &quot;{&quot;
17    567 │   circle {
18        ╵          ^
19

My Package.json is below:

1assets/.../variables.scss - Warning: Css Minimizer Plugin:  &gt; assets/.../variables.scss:6:0: warning: Unexpected &quot;$&quot;
2    6 │ $color-normal-gray:#8a8a8a;
3      ╵ ^
4
5assets/.../global.scss - Warning: Css Minimizer Plugin:  &gt; 
6assets/.../global.scss:285:2: warning: Expected identifier but found &quot;.&quot;
7    285 │   .dropdown-menu{
8        ╵   ^
9
10assets/.../global.scss - Warning: Css Minimizer Plugin:  &gt; 
11assets/.../global.scss:255:6: warning: Expected identifier but found &quot;*&quot;
12    255 │       *background-color: #d9d9d9;
13        ╵       ^
14
15assets/.../master.scss - Warning: Css Minimizer Plugin:  &gt; 
16assets/.../master.scss:567:8: warning: Expected &quot;:&quot; but found &quot;{&quot;
17    567 │   circle {
18        ╵          ^
19 &quot;dependencies&quot;: {
20    &quot;@angular/animations&quot;: &quot;^12.2.3&quot;,
21    &quot;@angular/cdk&quot;: &quot;^12.2.2&quot;,
22    &quot;@angular/common&quot;: &quot;^12.2.3&quot;,
23    &quot;@angular/compiler&quot;: &quot;^12.2.3&quot;,
24    &quot;@angular/core&quot;: &quot;^12.2.3&quot;,
25    &quot;@angular/forms&quot;: &quot;^12.2.3&quot;,
26    &quot;@angular/http&quot;: &quot;^7.2.16&quot;,
27    &quot;@angular/material&quot;: &quot;^12.2.3&quot;,
28    &quot;@angular/platform-browser&quot;: &quot;^12.2.3&quot;,
29    &quot;@angular/platform-browser-dynamic&quot;: &quot;^12.2.3&quot;,
30    &quot;@angular/router&quot;: &quot;^12.2.3&quot;,
31    &quot;@fortawesome/fontawesome-free&quot;: &quot;^5.15.4&quot;,
32    &quot;@ngrx/store&quot;: &quot;^6.1.0&quot;,
33    &quot;@okta/okta-angular&quot;: &quot;^3.0.1&quot;,
34    &quot;@okta/okta-auth-js&quot;: &quot;^4.7.1&quot;,
35    &quot;angular-datatables&quot;: &quot;^0.6.4&quot;,
36    &quot;angular-image-slider&quot;: &quot;0.0.8&quot;,
37    &quot;autobind-decorator&quot;: &quot;^2.4.0&quot;,
38    &quot;bootstrap&quot;: &quot;^4.6.0&quot;,
39    &quot;core-js&quot;: &quot;^2.5.4&quot;,
40    &quot;file-saver&quot;: &quot;^2.0.2&quot;,
41    &quot;gulp-cli&quot;: &quot;^2.3.0&quot;,
42    &quot;json-bigint&quot;: &quot;^1.0.0&quot;,
43    &quot;jsrsasign&quot;: &quot;^10.3.0&quot;,
44    &quot;lodash&quot;: &quot;4.17.10&quot;,
45    &quot;ng-simple-slideshow&quot;: &quot;^1.2.4&quot;,
46    &quot;ng2-scroll-to-el&quot;: &quot;^1.2.1&quot;,
47    &quot;ng2-search-filter&quot;: &quot;^0.4.7&quot;,
48    &quot;ngx-filter-pipe&quot;: &quot;^2.1.2&quot;,
49    &quot;ngx-logger&quot;: &quot;3.3.11&quot;,
50    &quot;ngx-order-pipe&quot;: &quot;^2.0.1&quot;,
51    &quot;ngx-pagination&quot;: &quot;^3.2.0&quot;,
52    &quot;pagination&quot;: &quot;file:src/app/packages/pagination-0.0.1.tgz&quot;,
53    &quot;rxjs&quot;: &quot;7.3.0&quot;,
54    &quot;rxjs-compat&quot;: &quot;^6.3.2&quot;,
55    &quot;sass&quot;: &quot;^1.36.0&quot;,
56    &quot;single-spa&quot;: &quot;^5.9.2&quot;,
57    &quot;single-spa-angular&quot;: &quot;^5.0.2&quot;,
58    &quot;systemjs&quot;: &quot;^6.8.3&quot;,
59    &quot;true-case-path&quot;: &quot;^1.0.3&quot;,
60    &quot;tslint&quot;: &quot;^6.0.0&quot;,
61    &quot;xlsx&quot;: &quot;^0.17.1&quot;,
62    &quot;zone.js&quot;: &quot;~0.11.4&quot;
63  },
64  &quot;devDependencies&quot;: {
65    &quot;@angular-builders/custom-webpack&quot;: &quot;^12.1.1&quot;,
66    &quot;@angular-devkit/build-angular&quot;: &quot;^12.2.2&quot;,
67    &quot;@angular-eslint/builder&quot;: &quot;12.3.1&quot;,
68    &quot;@angular-eslint/eslint-plugin&quot;: &quot;12.3.1&quot;,
69    &quot;@angular-eslint/eslint-plugin-template&quot;: &quot;12.3.1&quot;,
70    &quot;@angular-eslint/schematics&quot;: &quot;12.3.1&quot;,
71    &quot;@angular-eslint/template-parser&quot;: &quot;12.3.1&quot;,
72    &quot;@angular/cli&quot;: &quot;^12.2.2&quot;,
73    &quot;@angular/compiler-cli&quot;: &quot;^12.2.3&quot;,
74    &quot;@angular/language-service&quot;: &quot;^12.2.3&quot;,
75    &quot;@ng-bootstrap/ng-bootstrap&quot;: &quot;^10.0.0&quot;,
76    &quot;@types/bootstrap&quot;: &quot;^4.1.2&quot;,
77    &quot;@types/jasmine&quot;: &quot;2.8.6&quot;,
78    &quot;@types/jasminewd2&quot;: &quot;2.0.3&quot;,
79    &quot;@types/lodash&quot;: &quot;4.14.110&quot;,
80    &quot;@types/node&quot;: &quot;14.6.2&quot;,
81    &quot;@typescript-eslint/eslint-plugin&quot;: &quot;4.28.2&quot;,
82    &quot;@typescript-eslint/parser&quot;: &quot;4.28.2&quot;,
83    &quot;await&quot;: &quot;^0.2.6&quot;,
84    &quot;cheerio&quot;: &quot;^1.0.0-rc.2&quot;,
85    &quot;codelyzer&quot;: &quot;~4.2.1&quot;,
86    &quot;eslint&quot;: &quot;^7.26.0&quot;,
87    &quot;font-awesome&quot;: &quot;^4.7.0&quot;,
88    &quot;fs-promise&quot;: &quot;^2.0.3&quot;,
89    &quot;gulp&quot;: &quot;^4.0.2&quot;,
90    &quot;gulp-inline-css&quot;: &quot;^3.3.0&quot;,
91    &quot;gulp-inline-source&quot;: &quot;^4.0.0&quot;,
92    &quot;htmlhint-ng2&quot;: &quot;0.0.13&quot;,
93    &quot;husky&quot;: &quot;^1.3.1&quot;,
94    &quot;jasmine-core&quot;: &quot;~2.99.1&quot;,
95    &quot;jasmine-spec-reporter&quot;: &quot;~4.2.1&quot;,
96    &quot;karma&quot;: &quot;^6.3.4&quot;,
97    &quot;karma-chrome-launcher&quot;: &quot;^2.2.0&quot;,
98    &quot;karma-coverage-istanbul-reporter&quot;: &quot;^2.1.1&quot;,
99    &quot;karma-jasmine&quot;: &quot;~1.1.1&quot;,
100    &quot;karma-jasmine-html-reporter&quot;: &quot;^0.2.2&quot;,
101    &quot;karma-junit-reporter&quot;: &quot;^1.2.0&quot;,
102    &quot;mediaquery-text&quot;: &quot;1.0.7&quot;,
103    &quot;ng-bullet&quot;: &quot;^1.0.3&quot;,
104    &quot;protractor&quot;: &quot;^5.4.2&quot;,
105    &quot;puppeteer&quot;: &quot;^1.14.0&quot;,
106    &quot;sonar-scanner&quot;: &quot;^3.1.0&quot;,
107    &quot;ts-node&quot;: &quot;~5.0.1&quot;,
108    &quot;tslint&quot;: &quot;~5.9.1&quot;,
109    &quot;tslint-sonarts&quot;: &quot;^1.9.0&quot;,
110    &quot;typescript&quot;: &quot;^4.3.5&quot;
111  }
112

ANSWER

Answered 2021-Sep-08 at 10:30

I had the same problem. You should change the import of 'assets/.../variables.scss' to './assets/.../variables.scss'. In my case it was in styles.scss but it can be in every .scss file.

Source https://stackoverflow.com/questions/69040951

QUESTION

rxjs 7 update - Subject - Expected 1 arguments, but got 0

Asked 2021-Nov-19 at 10:13

I updated rxjs from version 6.x.x to 7.x.x, but following error appeared:

Error in src/app/app.component.ts (12:19) Expected 1 arguments, but got 0.

when trying to next an empty value to the Subject

1destroy$ = new Subject();
2
3constructor() {
4  this.destroy$.next(); // &lt;-- Expected 1 arguments, but got 0.
5}
6

ANSWER

Answered 2021-Jul-30 at 12:42

tl;dr:

Either typecast it with void:

1destroy$ = new Subject();
2
3constructor() {
4  this.destroy$.next(); // &lt;-- Expected 1 arguments, but got 0.
5}
6new Subject&lt;void&gt;();
7

or pass a fake value:

1destroy$ = new Subject();
2
3constructor() {
4  this.destroy$.next(); // &lt;-- Expected 1 arguments, but got 0.
5}
6new Subject&lt;void&gt;();
7this.destroy$.next(true);
8

Rxjs 7 changes

After checking the changelog and several github issues about this situation,

Subject: resolve issue where Subject constructor errantly allowed an argument (#5476) (e1d35dc)

Subject: no default generic (e678e81)

Changelog 7.0.0-beta.1 and the commit where empty value is removed from the tests

enter image description here

I realized that the solution was to either provide a value or simply typecast the Subject with <void> as in destroy$ = new Subject<void>() if you want to next it with an empty value.

Source https://stackoverflow.com/questions/68590899

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Angular

Share this Page

share link

Get latest updates on Angular