aspnetcore: .NET Core 3.0 + Angular 9 cli application called via the SpaServices extensions hangs in common configuration

Describe the bug

Running a .NET Core 3.0 + Angular 9 cli (version 9.0.0-rc.2 as of this post) with the angular cli build option progress set to false will hang until the StartupTimeout expires (default: 120 seconds)

To Reproduce

I created a repo with a bare bones .NET Core 3.0 + Angular 9 cli application to demo the bug. Simply clone, npm build the ClientApp folder, and dotnet run. Or you can follow the steps below to do this from scratch:

  1. Ensure you have .NET Core 3.0 installed
  2. Create a .NET Core application with the current Angular templates by typing: dotnet new angular -n HelloWorld
  3. Navigate to the ClientApp folder and install the Typescript helper functions required for Angular 9 by typing: npm install tslib@latest
  4. Update to Angular 9 by typing: ng update @angular/core @angular/cli --next
  5. Ensure the progress build option in the angular.json file is set to false
  6. Run the application by navigating back to the root folder and typing: dotnet run
  7. Launch a browser and navigate to: https://localhost:5001

The application will hang and eventually timeout.

Further technical details

This appears to be caused by a change in how ng serve outputs to the console in the new Angular 9 CLI. The AngularCliMiddleware makes a WaitForMatch() method call against the standard output to signify when the Angular assets have been generated and the web server is ready to receive requests (Line 84). However, unless the progress option is set to true in the angular.json file you never see the expected line.

UPDATE: Updated to .NET Core 3.1 and Angular 9.0.0-rc.5. Same issue. New, simpler workaround is to modify your npm start script to perform a simple echo prior to ng serve (see comment below)

UPDATE (6/5/2020): Lots of recent comments so I figured I’d share exactly what has worked for me with every release of .NET and Angular since my original post. Update your package.json like so:

  "scripts": {
    "ng": "ng",
    "start": "echo hello && ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  }

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 70
  • Comments: 77 (5 by maintainers)

Commits related to this issue

Most upvoted comments

We’ve moved this issue to the Backlog milestone. This means that it is not going to be worked on for the coming release. We will reassess the backlog following the current release and consider this item at that time. To learn more about our issue management process and to have better expectation regarding different types of issues you can read our Triage Process.

I’ve made a shamelessly hacky workaround which will do for now. Basically, I wrap the call to the Angular CLI in another Node script, and spoof the “open your browser on” message so that dotnet notices it.

You can try the workaround yourself:

  1. Edit your package.json to rename your start script to start:ng
  2. Add a new start script: "start": "node start-dotnet.js". Your package.json should look like
        "start":  "node start-for-dotnet.js",
        "start:ng": "ng serve [or whatever you had before]",
  1. Next to your package.json, add a file called start-dotnet.js with contents
// Hack to work around https://github.com/aspnet/AspNetCore/issues/17277

const { spawn } = require('child_process');

const portArgIndex = process.argv.indexOf('--port');

if (portArgIndex === -1) {
    throw new Error('Could not detect port number');
}

const port = process.argv[portArgIndex + 1];

console.log(`open your browser on http://localhost:${port}`);

const child = spawn(`cmd`, ['/c', `npm.cmd run start:ng -- --port ${port}`]);

console.log('Angular CLI started on PID', child.pid);

child.stdout.on('data', x => console.log(x && x.toString()));

child.stderr.on('data', x => console.error(x && x.toString()));

const sleep = () => {
    console.log('[Node.js keepalive]');
    setTimeout(sleep, 10000);
}

sleep();

Looks that aspnet team no longer cares about the Angular template… net5 still installs angular 8 even tho angular 11 is almost out.

Still waiting on a fix for this. The echo solution doesn’t work for me, but the node does. It’s pretty ugly. Not sure if angular needs to change the way they emit to the console or the spa service extension needs to change the way it listens.

For anyone wanting to use Angular 9 with a netcore3 app, i would recommend going back to angular 8 until this gets resolved. Otherwise the node hack from @benelliott worked for me

I am using .NET Core 3.1 and am encountering the same issue using @angular/cli@~9.0.0-rc.5. I never get the line expected by the AngularCliMiddleware from the Angular CLI. I have had it work correctly intermittently with both --progress=true and --progress=false.

I have zero clue as to why the following workaround works, but I consistently get the expected behavior if I add any statement that outputs to stdout prior to ng serve . My package.json script is echo hello && npm serve --progress=false, and I get the following reliably:

image

EDIT: Adding environment info:

  • Windows 10 build 18363
  • Node.js 12.13.0
  • Visual Studio Code 1.40.2
  • dotnet CLI 3.1.100
  • @angular/cli 9.0.0-rc.5

Every few days both new and senior .NET developers stumble upon this bug and post a comment to share their frustration. Although I can sympathize, as the OP it surprises me since I thought I did a decent job describing various workarounds including the simplest one that has worked for me with every release of .NET or Angular since my original post:

update the scripts section in package.json by adding an echo statement prior to ng serve

Lately, however, some of the posts have expressed concerns of back porting the “fix” to .NET 3.x so I wanted to share my thoughts:

  1. It can be argued that updating the dotnet templates to include the echo statement by default is harmless enough, however, that would mask the underlying issue which I guess is why that simple change hasn’t been done.

  2. More importantly, this bug only surfaces during the development of a .NET application using the SpaServices extensions since that is when you would proxy requests to a local instance of your Angular app served up via ng serve. When you actually publish your .NET application, your Angular app gets compiled and those artifacts are published to a dist folder which the SpaServices extensions will serve as static files. The Angular CLI at this point is no longer in the picture.

Hope that clears up the back porting concern.

I will also update the original post to better describe the simplest workaround.

I run into no issues just using echo something && ng serve, but certainly will keep this in mind if I or anyone else I’m working with run into this issue again; when I get home I will see what the behavior on other operating systems looks like.

What worked for me was changing “ng serve” to “ng serve --host 0.0.0.0” in package.json “start”

I recently upgraded from Angular 10.1.1 to 10.2.3, and this problem inexplicably got a lot more frequent, to the point of being unusable. This is with the echo and progress solutions in place. So I tried upgraded my Microsoft.AspNetCore.* NuGet packages to 3.1.10, and I also tried upgrading Angular to 11.0.4. With those upgrades done, I am unable to get any solution mentioned above to work aside from “Run “ng serve” independently” from the Docs.

That is to say, for me, this problem now has no known solution other than completely abandoning the automatic background Ng CLI process, as it is now non-functional 100% of the time. I can’t explain why or who it suddenly broke except for the upgrade from Angular 10.1.1 to 10.2.3.

It’s unthinkable to me that a problem this bad has been ignored by MSFT for over a year now.

@mkArtakMSFT, EventedStreamReader is already fixed in master, related issues #6306, #6146. However nuget package Microsoft.AspNetCore.SpaServices.Extensions 3.1.3 does not include these fixes:

https://github.com/dotnet/aspnetcore/blob/e81033e094d4663ffd227bb4aed30b76b0631e6d/src/Middleware/SpaServices.Extensions/src/Util/EventedStreamReader.cs

angular.json -> architect -> build -> options -> “progress”: true

worked for me

For me, none of the solutions posted here worked, not even changing “ng serve” to “ng serve --host 0.0.0.0” in package.json “start”

But another change in the same place found in:

https://github.com/angular/angular-cli/issues/16961

change “start”: “ng serve” to “start”: “echo Starting… && ng serve”

worked

@elianora suggestion of modifying the npm start script in your package.json by adding an echo statement prior to ng serve is enough to notify the AngularCliMiddleware the angular dev server is running. This is a better workaround than setting the progress flag to true.

BTW, can’t see how it would matter but I did notice a subtle difference in how the Angular CLI outputs build info between Angular 8 and 9. Specifically, the Date and Hash information comes after the chunk information in Angular 9, where as it is the first line in Angular 8.

info: Microsoft.AspNetCore.SpaServices[0]
chunk {main} main.js, main.js.map (main) 60.7 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 140 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 9.94 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 2.99 MB [initial] [rendered]
Date: 2019-12-06T04:20:45.321Z - Hash: 6ee5d8996273b040afe7 - Time: 5917ms <-- This is now on one line and in a new location in Angular 9
Of course the actual string the AngularCliMiddleware is searching for: “open your browser on” is still being emitted by the angular_devkit package (Line 303).

I have tried all of the workarounds, but another thing that worked for me was running Visual Studio as an admin which seemed to fix the issue without any code changes. Does this work for anyone else?

The workarounds that have worked for me are:

ng serve --verbose also helps!

The echo workaround works for me too… so my workaround might be slight overkill 😃

I don’t fully get why it fixes it though…

EDIT: it seems that when I add the --aot flag, the echo workaround no longer helps. I have to use the NodeJS workaround in this case.

The only workaround that worked for us (.NET 3.1.11 + Angular 11.0.5): https://github.com/angular/angular-cli/issues/16961#issuecomment-620022661

@mkArtakMSFT

Sorry that this is taking this long. We’ve have been busy with Blazor WebAssembly during last several months. The good news is that we’re getting to the end of it and will investigate this in approximately a month. Just moved this to 5.0-preview5 release to make sure this doesn’t get ignored any further, given the amount of feedback this has accumulated.

This will not be fixed in 3.x? It’s a bummer if that’s the case since 5.0 is not a LTS version and it will be a great challenge to use in products that customers buy and run because of the “short” support window.

If we look into the future Angular will be at version 12 or so when .NET 6 is ready for release so if we have breaking changes in every other Angular release similar to this and only get fixes in majour releases we will have a big problem.

.NET 6 is planned to be released as LTS in end of 2021 and Angular 9 is end of life in Aug 06, 2021 but is end of what they call "Active Support"already Aug 06, 2020. That might give us a situation where this fix is not available at all during Angular 9s entire “active support” lifespan…?

https://angular.io/guide/releases

Sorry that this is taking this long. We’ve have been busy with Blazor WebAssembly during last several months. The good news is that we’re getting to the end of it and will investigate this in approximately a month. Just moved this to 5.0-preview5 release to make sure this doesn’t get ignored any further, given the amount of feedback this has accumulated. /cc @danroth27

I have zero clue as to why the following workaround works, but I consistently get the expected behavior if I add any statement that outputs to stdout prior to ng serve . My package.json script is echo hello && npm serve --progress=false, and I get the following reliably:

@elianora, according to the screenshot, the command is echo hello && ng serve --progress=false (instead of npm serve)

It’s fine as a workaround for now, thanks.

Due to a dependency, I’m unable to upgrade my .NET Core 2.2 app to 3 yet, so when I upgraded to Angular 9 I ran into this issue as well. The echo solution saved me; thank you @elianora !

Side note: I don’t have progress set to false. It is true and I still ran into this issue, so I don’t know that that’s a factor here.

@heart2friend as a last try you can always start the angular process in a different terminal and switch the spa service to running on developer port.

After trying a lot, what finally worked for me was setting echo something && ng serve and then under debug button (by clicking the arrow down button next to project name) in Visual Studio, select project name instead of IIS Express. I have used this setup on 2 or 3 projects without fail.

Bfff… I’ve just seen that I’m not alone here… 6 AM and still working.

The angular app created via Visual Studio 2019 16.6 Preview is version 8 not 9. Will it support Angular 9 in the future?

We haven’t added official support for Angular 9 yet. The issue I’ve referenced above is tracking that work. We’ll just make sure this issue is resolved when doing that.

I’ve made a shamelessly hacky workaround which will do for now. Basically, I wrap the call to the Angular CLI in another Node script, and spoof the “open your browser on” message so that dotnet notices it.

You can try the workaround yourself:

  1. Edit your package.json to rename your start script to start:ng
  2. Add a new start script: "start": "node start-dotnet.js". Your package.json should look like
        "start":  "node start-for-dotnet.js",
        "start:ng": "ng serve [or whatever you had before]",
  1. Next to your package.json, add a file called start-dotnet.js with contents
// Hack to work around https://github.com/aspnet/AspNetCore/issues/17277

const { spawn } = require('child_process');

const portArgIndex = process.argv.indexOf('--port');

if (portArgIndex === -1) {
    throw new Error('Could not detect port number');
}

const port = process.argv[portArgIndex + 1];

console.log(`open your browser on http://localhost:${port}`);

const child = spawn(`cmd`, ['/c', `npm.cmd run start:ng -- --port ${port}`]);

console.log('Angular CLI started on PID', child.pid);

child.stdout.on('data', x => console.log(x && x.toString()));

child.stderr.on('data', x => console.error(x && x.toString()));

const sleep = () => {
    console.log('[Node.js keepalive]');
    setTimeout(sleep, 10000);
}

sleep();

While waiting to proper fix, i think this is best hack that seems working fine. thank you @benelliott

What worked for me was changing “ng serve” to “ng serve --host 0.0.0.0” in package.json “start”

this worked for me, thankss

Mine works by editing "start": "ng serve --port 4200"

What worked for me was changing “ng serve” to “ng serve --host 0.0.0.0” in package.json “start”

this worked for me

const child = spawn(`cmd`, ['/c', `npm.cmd run start:ng -- --port ${port}`]);

This line is Windows-specific, the Linux equivalent would be something along the lines of (but possibly not exactly)

const child = spawn(`npm`, ['run', `start:ng -- --port ${port}`]);

Closing this as we’ve changed the approach how the SPA project templates work now. You can find more details about this in the issue tracking that work: https://github.com/dotnet/aspnetcore/issues/27887

@benelliott Thanks, your fix is the only solution that works for me. There is one issue though. The Node.js process is kept alive after closing the debug session in VS Code. If I restart a few times I soon run out of memory and the CPU usage skyrockets.

Is there a way to kill the Node.js process?

Right now I’m debating whether to give up and just start the .Net part and frontend parts separately.

@heart2friend as a last try you can always start the angular process in a different terminal and switch the spa service to running on the developer port.

Thank you @svrooij it worked. This shouldn’t be the ideal solution but it’s working is lot more for me.

For those who are struggling with same problem here is the interim solution

  1. Run the angular app using the command prompt (ng serve) from the ClienApp directory.
  2. Replace spa.UseAngularCliServer(npmScript: “start”); with spa.UseProxyToSpaDevelopmentServer(“http://localhost:4200”); in Startup.cs file.

app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, // see https://go.microsoft.com/fwlink/?linkid=864501

            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {
                //spa.UseAngularCliServer(npmScript: "start");
                spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
            }
        });

This works like a charm!

@heart2friend updating from .Net Core 3.1 to .Net5 fixed it for me.

I have this bug only on debugging (F5) on .NET 3.1+Angular 11.0.5.only work after I try for 9 or 10 times,too hard to debug… tried all fixes but none works

FWIW, I was able to fix this in my project by forking my own copy of the Microsoft.AspNetCore.SpaServices.Extensions project (from the 2.1 release branch), and then dropping in the internal EventedStreamReader class from the .net 5 release branch. This seems to solve the problem where it never sees the line saying “open your browser…”.

taskkill /f /im node.exe will close all running node processes, I was wondering if this could be added to .csproj file like <Exec Command="taskkill /im node.exe /f"></Exec> and have it executed after each debug session ends?

hi, waiting for fix, this works under win os; edit package.json like this:

“start”: “@echo open your browser on http://localhost:4200 & ng serve & rem”,

Hello, I had the same problem and I performed several tests on different projects and simply saving some change in a file inside the ClientApp folder, it makes angular recompile and then VS2019 / VSCode recognizes the node server, without changing any configuration. I comment this in case it helps anyone.

I also tested in the solution of the repo miguellira/Angular9CliTemplateBug with VS 2019 Community and VS Code and works.

Echo solution works sometimes. Some other times, it just hangs after logging the chunks without printing this message:

info: Microsoft.AspNetCore.SpaServices[0] : Compiled successfully.

But as verbose mode extremely pollutes the console, it would be better to detect readiness by a background HTTP GET instead of parsing the console output.