Category: Angular

Windows terminal + Powershell to run IDE, Angular, .NET Core

I work at http://github.com/ignatandrei/BlocklyAutomation – and every time I need to run Angular , Visual Studio Code IDE and .NET Core run ( and Visual Studio  sometimes  – it is more web based)

Also, sometimes I need to run in a container – to install globally something that I do not want to have in my PC.

So  I have 1 windows terminal command to run those :

First one

wt new-tab   –title RootSource –suppressApplicationTitle -p “Windows PowerShell” -d . cmd /k “cd src && code . && powershell” ;split-pane  –title Angular –suppressApplicationTitle -V -p “Windows PowerShell” -d . cmd /k “cd src &&  npm run start –watch && powershell” ;split-pane  –title LocalAPI_NetCore –suppressApplicationTitle -V -p “Windows PowerShell” -d . cmd /k “cd src/Local/LocalAPI/LocalAPI && dotnet watch run”

As you see , I have

code .

to run VSCode,

npm run start –watch

to run Angular and

dotnet watch run

to run dotnet.

Second one:

wt new-tab -p “Windows PowerShell” -d . ;split-pane -p “Windows PowerShell” -d . cmd /k “cd src && devcontainer open .”

The second it just works with devcontainer  – if you are interested in sources, see https://github.com/ignatandrei/BlocklyAutomation/tree/main/src/.devcontainer 

With those, I can start my developer environment fast ( how fast, that depends on my PC)

Developer choices Web => Windows application

So I have an Angular application – basically, a macro for your WebAPI – see https://ignatandrei.github.io/BlocklyAutomation/ . I want to transform into an Windows Application and have also deployed to Windows Store.

Attempt 1 : embed as a resource a .NET Core WebAPP and deploy to Windows Store. Not really –  the validation part of Store realizes this trick

Attempt2 : Electron – must rewrite window.prompt : https://github.com/electron/electron/issues/472

Attempt3 : Let’s see Blazor – https://github.com/dotnet/MobileBlazorBindings/  – however , it has just WPF, not UWP .

Attempt3: WebView2 –  https://github.com/MicrosoftEdge/WebView2Samples . It has an UWP. However, I realize that it does not have redirect … so routes in Angular will be difficult – if not intercepting 404 and serving the same index.html.

Attempt4: PWA : https://docs.microsoft.com/en-us/windows/uwp/publish/pwa/overview – yes, but my app it was Angular 12. Pass to 13 ( and force some unresolved dependencies ) take me the rest of the  day .

So I am at PWA now.

And Angular with https://www.pwabuilder.com/ is pretty impresive

What I do not have yet: ASP.NET Core downloading as Windows Store application with PWA and Controllers …

UNIQUE ID inside an Angular Component

If you use an id for a HTML element inside your angular component and then use

document.getElementById

to retrieve it, bear in mind that someone can have multiple instances of your component on the same page. So here is a simple trick to deal with

1. In the HTML component put

<div [id]=”‘htmlOutput’+myId”></div>

2. In the ts file put

export class MyComponent{

static id:number=0;

myId:number=0;

constructor(/*arguments*/){

this.myId=++DisplayBlocklyComponent.id;

}

}

and for retrieving the HTML element

document.getElementById(‘htmlOutput’+this.myId)

That is all;

Integrating SPA ( Angular, React, Vue) with .NET Core for production

If you have a .NET Core WebAPI application ( that only serves data ) and  a SPA application ( Angular, Vue,  React) you can have just one application following this 2 steps:

1.  In .NET Core add in Startup.cs ( with using Microsoft.AspNetCore.Builder from Microsoft.AspNetCore.StaticFiles )

app.UseDefaultFiles();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
             {
                

            // If you know the endpoints, put it here

           //endpoints.MapFallbackToFile(“dbodepartment/{**slug}”,”/index.html”);
                         
                 endpoints.MapControllers();
                 endpoints.MapFallbackToFile(“{**slug}”, “/index.html”);
});

2. Compile the SPA to index.html, deploy in wwwroot with the js and css

( yes, you should modify the endpoint for data when compiling to / –  for Angular see my previous post , http://msprogrammer.serviciipeweb.ro/2020/09/14/angular-base-href-for-web-desktop-mobile-and-paths-for-services/ )

Angular base href for web, desktop, mobile ( and paths for services)

My current stack is .NET Core (backend) + Angular ( frontend) ( For  database, it is usual SqlServer – but I use Sqlite, Mongo, local storage ….)

With Angular I can have Mobile application ( by Cordova ) and Windows Desktop ( with Electron)

But the BaseHref it is a PIA …. even for Web, if you host into a virtual directory .

So this is my setup in 2 steps. Maybe could be somehow easy, but… I did not discover something better yet.

Step 1: Create a favicon.svg into the assets folder

Step 2: Instead of

<base href=”/”>

put

<!– <base href=”/”> –>

<script>

var isCordovaApp = !!window.cordova;

var isWindowApp = !!window.MSApp;

if (isCordovaApp) {

        hrefApp = “.”;

      }

if (isWindowApp) {

        hrefApp = “./”;

      }

if (!(isCordovaApp || isWindowApp)) {

var baseHref = window.location.href.split(“/”);

while (true) {

          baseHref.pop();

          hrefApp = baseHref.join(“/”) + “/”;

// window.alert(hrefApp);

var request = new XMLHttpRequest();

          request.open(“GET”, hrefApp + “favicon.svg”, false);           request.send(null);

if (request.status === 200) {

if(request.responseText.indexOf(“meta name=”)<1){

              console.log(`found ${hrefApp} `);

break;

            }

          }

        }

      }

    document.write(‘<base href=”‘ + hrefApp+ ‘” />’);

</script>

And this is all!

For correct path of services , I do this

For each service , I construct with

constructor(@(Inject)(APP_BASE_HREF) baseHref: string, private client: HttpClient)

this.baseUrl = environment.webAPIUrl + baseHref ;

and  when I call a function

const url = this.baseUrl+’api/WeatherForecast;

In the envoronment.ts I have

export const environment = {

  production: false,

  webAPIUrl: ‘http://localhost:5000’

};

and in the environment.prod.ts I do have

export const environment = {

  production: true,

  webAPIUrl: ”

};

One more thing: to inject APP_BASE_HREF , I must have into app.modue.ts

providers: [{

    provide: APP_BASE_HREF,

    useFactory: (s: PlatformLocation) => s.getBaseHrefFromDOM(),

    deps: [PlatformLocation]

  }

That’s all! ( yes , I know it is a bit complicated….)

Interceptor in Angular–Error service

Similar video at https://www.youtube.com/watch?v=ajosuyhcKV4

I need to inform the user when the application is loading data with error ( i.e. the backend is giving some error back). And do it seamlessly , every time.

I found the documentation about interceptors at https://angular.io/api/common/http/HttpInterceptor”– and you can find more searching on google /  bing .

Also, I have the need to display this no matter in what page  – so a service will help


import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ErrorService {

  private err: Subject<string>;

  constructor() {
    this.err = new Subject<string>();
  }

  public NextError(): Observable<string> {

    return this.err.asObservable();

  }

  public setNextError(str: string) {

    this.err.next(str);

  }

}


Now the interceptor

import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse
} from '@angular/common/http';

import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { ErrorService } from './error.service';

/** Pass untouched request through to the next request handler. */
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {


  constructor(private err: ErrorService ) {


  }
  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpEvent<any>> {

    return next.handle(req).pipe(
        catchError( err => this.handleError(req, err))
    );
  }

  private handleError(req: HttpRequest<any>, error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      const str = 'An error occurred:' +   error.error.message;
      console.log(str);
      this.err.setNextError(str);

    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      const str =
        `Backend returned code ${error.status}, ` +
        `body was: ${JSON.stringify(error.error)}`;
      console.log(str);
      this.err.setNextError(str);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  }
}


The class itself

@Component({
  selector: 'app-covid-navig',
  templateUrl: './covid-navig.component.html',
  styleUrls: ['./covid-navig.component.css']
})
export class CovidNavigComponent  {
  public isLoading = false;
  constructor(private breakpointObserver: BreakpointObserver
    ,         private err: ErrorService
    ,         private snackBar: MatSnackBar
    ,         private ls: LoaderService) {
    this.err.NextError().pipe(
      tap(it => {
        this.snackBar.open(it, 'ERROR', {
          duration: 5000,
        });
      }),
      shareReplay()
    ).subscribe();
    this.ls.loading$().subscribe(it => this.isLoading = it);

  }

And this is all !( besides registering the interceptors in a barrelInterceptors.ts

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { ErrorInterceptor } from './ErrorInterceptor';
import { LoaderInterceptor } from './LoaderInterceptor';





/** Http interceptor providers in outside-in order */
export const httpInterceptorProviders = [
  { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
  { provide: HTTP_INTERCEPTORS, useClass: LoaderInterceptor, multi: true },
];

and register to the appmodule.ts


providers: [
    httpInterceptorProviders,
  ] 

Interceptor in Angular–loader and service

Video at https://www.youtube.com/watch?v=ajosuyhcKV4

I need to inform the user when the application is loading data – and when it is not loading anymore. Usually , the data comes from a backend via an HTTP call– and will be some timeout before it becomes available. So – simple – just intercept this and then show some spinning to the user, right ?

I found the documentation about interceptors at https://angular.io/api/common/http/HttpInterceptor – and you can find more searching on google /  bing .

Also, my inspiration was started from here:

https://grensesnittet.computas.com/loading-status-in-angular-done-right/

But , if we intercept, how to distribute ? The services singleton in Angular will provide help

import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LoaderService {
  constructor() {
    this.s = new Subject<boolean>();

  }

  public s: Subject<boolean>;
  public loading$(): Observable<boolean> {
    return this.s.asObservable();
  } 

  public isLoading(b: boolean) {
    this.s.next(b);
  }

}

So I have created the HttpInterceptor to call the service , like here:

import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse
} from '@angular/common/http';

import { Observable, throwError } from 'rxjs';
import { catchError, tap, finalize } from 'rxjs/operators';

import { LoaderService } from './loader.service';

/** Pass untouched request through to the next request handler. */
@Injectable()
export class LoaderInterceptor implements HttpInterceptor {

  private requests: HttpRequest<any>[] = [];
  constructor(private ls: LoaderService ) {


  }
  removeRequest(req: HttpRequest<any>) {
    const i = this.requests.indexOf(req);
    if (i >= 0) {
      this.requests.splice(i, 1);
    }
    this.ls.isLoading(this.requests.length > 0);
  }
  // https://grensesnittet.computas.com/loading-status-in-angular-done-right/
  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpEvent<any>> {
    this.requests.push(req);
    this.ls.isLoading(true);
    return next.handle(req).pipe(
        finalize(() => this.removeRequest(req))
    );
  }

}

And now it is simple to display in any page: – in the HTML

<mat-spinner *ngIf="isLoading"></mat-spinner>

and in the .ts pass in the constructor via DI

@Component({
  selector: 'app-covid-navig',
  templateUrl: './covid-navig.component.html',
  styleUrls: ['./covid-navig.component.css']
})
export class CovidNavigComponent  {
  public isLoading = false;
  constructor(private breakpointObserver: BreakpointObserver
    ,         private err: ErrorService
    ,         private snackBar: MatSnackBar
    ,         private ls: LoaderService) {
    this.err.NextError().pipe(
      tap(it => {
        this.snackBar.open(it, 'ERROR', {
          duration: 5000,
        });
      }),
      shareReplay()
    ).subscribe();
    this.ls.loading$().subscribe(it => this.isLoading = it);

  }

Simple , right ?

Covid Data – making the application – part 4

Now I need an application. The first version was a simple html file with Data Tables ( https://datatables.net/ ). You can find at https://ignatandrei.github.io/WFH_Resources/output.html . It is a simple table with search / filter and sorting.

The next , with help from Bogdan we have  started an Angular application , deployed at https://ignatandrei.github.io/WFH_Resources within the docs folder : http://github.com/ignatandrei/wfH_Resources/docs

For Angular the only thing that gives me problems were the charts : https://ignatandrei.github.io/WFH_Resources/covidData/Italy-Romania  . I used the https://www.chartjs.org/ . It is very flexible and doing all that I have wanted. The only problem : it retains previous graphic. I have to manually clear the canvas before rendering again the chart.

if (this.lineChart1) {

this.lineChart1.destroy();

}

You can find the charts at https://ignatandrei.github.io/WFH_Resources/covidData/Italy-Romania

Caching data frontend- Angular interceptors for Observable–part 48

Now I want to cache data for fast loading site- if it comes next time with the same browser, should have some data returned fast – and then load from HTTP. So first return from cache, then make the request

So I need to create an HTTP interceptor to cache things-  fortunately, Angular already provide tutorial about this: https://angular.io/guide/http#intercepting-requests-and-responses  – see CachingInterceptor. And the question is how to return 2 results ( of the same type ) from the same function  ?  Fortunately, the answer is: Observable ! ( It took me a while to figure that intercept returns Observable …). Also, when making the http request, the code should also store the result for the next time.

So I need to combine the 2 observables, one from cache and one from HTTP result  – or I can use startWith ( to start with the value).

First, I wanted to put into a static dictionary ( key: url, value: value of the request) the data. It did not work. Why ? Because of this

 

static cache: Map<string, any> = new Map<string, any>();

//code for finding if we have something in the case

if (CachingInterceptor.cache.has(req.url)) {

//code to put into the cache

this.cache[req.url] = event.body; // Update the cache.

 

Can you spot the error ? ( Yes, I know: Dictionary in C# has tricked my mind)

Last line should be this:

CachingInterceptor.cache.set(url,event.body); // Update the cache.

Now the caching works – but only for local .  And only in memory .

You can find the commit at https://github.com/ignatandrei/InfoValutar/commit/2bde8130add59c84d11d7348ad0a88bb576e356a

Infovalutar

And one hour passes...
(This is the result of 1 hour per day auto-challenge as a full cycle developer for an exchange rates application)
( You can see the sources at https://github.com/ignatandrei/InfoValutar/ )
NrPost 
1Start
2Reading NBR from internet
3Source control and build
4Badge and test
5CI and action
6Artifacts and dotnet try
7Docker with .NET Try
8ECB
9Intermezzo - Various implementations for programmers
10Intermezzo - similar code - options
11Plugin implementation
12GUI for console
13WebAPI
14Plugin in .NET Core 3
15Build and Versioning
16Add swagger
17Docker - first part
18Docker - second part
19Docker - build Azure
20Pipeline send to Docker Hub
21Play with Docker - online
22Run VSCode and Docker
23Deploy Azure
24VSCode see tests and powershell
25Code Coverage
26Database in Azure
27Sql In Memory or Azure
28Azure ConString, RSS
29Middleware for backward compatibility
30Identical Tables in EFCore
31Multiple Data in EFCore
32Dot net try again
33Start Azure Function
34Azure function - deploy
35Solving my problems
36IAsyncEnumerable transformed to IEnumerable and making Azure Functions works
37Azure functions - final
38Review of 37 hours
39Last Commit in AzureDevOps
40Create Angular WebSite
41Add static Angular to WebAPI .NET Core
42Docker for Angular
43Angular and CORS
44SSL , VSCode, Docker
45Routing in Angular
46RxJS for Routing
47RxJs Unsubscribe

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.