Tag: Debug

How to Troubleshoot Common Angular Errors

Learn how to optimize your troubleshooting tools and became aware of the common Angular errors you might encounter while developing applications.

Debugging Tools

In this article, you will intentionally introduce an easy-to-make mistake so that you can become familiar with real-life errors that can happen while developing your applications and gain a solid understanding of the tool that makes make you an effective developer.

Now pretend that you have made an innocent mistake when copying and pasting the URL from the API documentation page on OpenWeatherMap.org and forgot to add http:// in front of it. This is an easy mistake to make:

src/app/weather/weather.service.ts

...

return this.httpClient

  .get<ICurrentWeatherData>(

    `api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${environment.appId}`

  ).pipe(map(data => this.transformToICurrentWeather(data)))

...

Your app will compile successfully, but when you inspect the results in the browser, you won’t see any weather data. In fact, it seems like the Current Weather component is not rendering at all, as you can see in the image below:

Current Weather Does Not Render

There are many ways to debug angular errors for application or any JavaScript application here are some of this:

Debugging with Chrome Developer Tools

You can use the Google Chrome browser because of its cross-platform and consistent developer tools with helpful extensions.

Open Chrome Developer Tools (dev tools) on macOS by pressing option + ⌘ + I or on Windows by pressing F12 or CtrlShift + I.

As a best practice, you write code with VS Code and the browser open side by side, while the dev tools are also open in the browser. There are several good reasons for practicing side-by-side development:

  • Fast feedback loops: With live-reloading, you see the end result of your changes very quickly
  • Laptops: A lot of developers do most of their development on a laptop and a second monitor is a luxury
  • Attention to responsive design: As you may have limited space to work with, you can constantly pay attention to mobile-first development, fixing desktop layout issues after the fact
  • Awareness of network activity: To enable you to quickly see any API call errors and also ensure that the amount of data that is being requested remains in line with your expectations
  • Awareness of console errors: To enable you to quickly react and troubleshoot when new errors are introduced

Observe how side-by-side development looks like:

Side-by-side development with live-reloading running

Note that ultimately, you should do what works best for you. With the side-by-side setup, you will frequently find yourself toggling VS Code’s Explorer on and off and resizing the dev tools pane to a larger or smaller size depending on the specific task at hand. To toggle VS Code’s Explorer, click on the Explorer icon circled in the preceding screenshot.

Just as you can do side-by-side development with live-reloading using npm start to solve angular errors. You can get the same kind of fast feedback loops for unit testing using npm test:

Side-by-side development with unit testing

With the side-by-side unit testing setup, you can become very effective in developing unit tests.

Optimizing Chrome Dev Tools

For the side-by-side development with live-reloading to work well, you need to optimize the default dev tools experience:

Optimized Chrome Developer Tools

Looking at the preceding figure, you will note that numerous settings and information radiators are highlighted:

  1. Have the Network tab open by default so that you can see network traffic flowing.
  2. Open the dev tools settings by clicking on the
  3. Click on the right-hand side icon so that dev tools dock on the right-hand side of Chrome. This layout gives more vertical space, so you can see more network traffic and console events at once. As a side benefit, the left-hand side takes the rough size and shape of a mobile device.
  4. Toggle on large request rows and toggle off overview to see more of the URL and parameters for each request and gain more vertical space.
  5. Check the option Disable cache, which will force reload every resource when you refresh a page while the dev tools are open. This prevents bizarre caching errors from ruining your day.
  6. You will mostly be interested in seeing XHR calls to various APIs, so click on XHR to filter results.
  7. Note that you can glance at the number of console errors in the upper-right corner as 12. The ideal number of console errors should be at all times.
  8. Note that the top item in the request row indicates that there’s an error with status code 404 Not Found.
  9. Since you’re debugging an Angular application, the Augury extension has been loaded.

With your optimized dev tools environment, you can now effectively troubleshoot and resolve the application error from earlier.

Troubleshooting network issues

There are three visible issues with the app at this state:

  • The component details aren’t displaying
  • There are numerous console errors
  • The API call is returning a 404 not found error

Begin by inspecting any network errors, since network errors usually cause knock-on effects:

  1. Click on the failing URL in the Network
  2. In the Details pane that opens to the right of the URL, click on the Preview
  3. You should see this:
Cannot GET /api.openweathermap.org/data/2.5/weather

By just observing this error message, you will likely miss the fact that you forgot to add the http:// prefix to the URL. The bug is subtle and certainly not glaringly obvious.

  1. Hover over the URL and observe the full URL, as shown:

Inspecting Network Errors

As you can see, now the bug is glaringly obvious. In this view, you will get to see the full URL, and it becomes clear that the URL defined in weather.service.ts is not fully qualified, so Angular is attempting to load the resource from its parent server, hosted on localhost:5000, instead of going over the web to the right server.

Investigating console errors

Before you fix this issue, it is worthwhile to understand the knock-on effects of the failing API call:

  1. Observe the console errors:

Dev Tools Console Error Context

The first element of note here is the ERROR CONTEXT object, which has a property named DebugContext_. The DebugContext_ contains a detailed snapshot of the current state of your Angular application when the error happened. The information contained within DebugContext_ is light years ahead of the amount of mostly unhelpful error messages AngularJS generates.

Note that properties that have the value (…) are property getters, and you must click on them to load their details. For example, if you click on the ellipsis for componentRenderElement, it will be populated with the app-current-weather element. You can expand the element to inspect the runtime condition of the component.

  1. Now scroll to the top of the console.
  2. Observe the first error:
ERROR TypeError: Cannot read property 'city' of undefined

You have probably encountered the TypeError before. This error is caused by trying to access the property of an object that is not defined. In this case, CurrentWeatherComponent.current is not assigned to an object, because the http call is failing. Since current is not initialized and the template blindly tries to bind to its properties like {{current.city}}, you will get a message saying property ‘city’ of undefined cannot be read. This is the kind of knock-on effect that can create many unpredictable side-effects in your application. You must proactively code to prevent this condition.

Karma, Jasmine, and Unit Testing errors

When running tests with the ng test command, you will encounter some high-level errors that can mask the root cause of the actual underlying errors.

The general approach to resolving errors should be inside out, resolving child component issues first and leaving parent and root components for last.

Network Error

Network errors can be caused by a multitude of underlying issues:

NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'ng:///DynamicTestModule/AppComponent.ngfactory.js'.

Working inside out, you should implement test doubles of services and provide the fakes to the appropriate components. However, in parent components, you may still encounter errors even if you correctly provided fakes.

Generic ErrorEvents

Error events are generic errors that hide the underlying cause:

[object ErrorEvent] thrown

To expose the root cause of a generic error, implement a new test:debug script:

  1. Implement test:debug, as shown, in json:
package.json

...

"scripts": {

  ...

  "test:debug": "ng test --sourcemaps=false",

  ...

}
  1. Execute npm run test:debug.
  2. Now the Karma runner will likely reveal the underlying issue.
  3. If necessary, follow the stack trace to find the child component that may be causing the issue.

Note that if this strategy is not helpful, you may be able to glean more information on what’s going wrong by breakpoint debugging your unit tests.

Debugging with Visual Studio Code

You can also debug your Angular application, Karma, and Protractor tests from directly within Visual Studio Code. First, you need to configure the debugger to work with a Chrome debugging environment, as illustrated:

VS Code Debugging Setup

  1. Click on the Debug
  2. Expand the No Configurations drop-down and click on Add Configuration….
  3. In the Select Environment select box, select Chrome.

This will create a default configuration in the .vscode/launch.json file. You can modify this file to add three separate configurations.

  1. Replace the contents of jsonwith the following configuration:
.vscode/launch.json

{

  "version": "0.2.0",

  "configurations": [

    {

      "name": "npm start",

      "type": "chrome",

      "request": "launch",

      "url": "http://localhost:5000/#",

      "webRoot": "${workspaceRoot}",

      "runtimeArgs": [

        "--remote-debugging-port=9222"

        ],

      "sourceMaps": true

    },

    {

      "name": "npm test",

      "type": "chrome",

      "request": "launch",

      "url": "http://localhost:9876/debug.html",

      "webRoot": "${workspaceRoot}",

      "runtimeArgs": [

        "--remote-debugging-port=9222"

        ],

      "sourceMaps": true

    },

    {

      "name": "npm run e2e",

      "type": "node",

      "request": "launch",

      "program": "${workspaceRoot}/node_modules/protractor/bin/protractor",

      "protocol": "inspector",

      "args": ["${workspaceRoot}/protractor.conf.js"]

    }

  ]

}
  1. Execute the relevant CLI command like npm start, npm test, or npm run e2ebefore you start the debugger.
  2. On the Debugpage, in the Debug drop-down, select npm start and click on the green play icon.
  3. Observe that a Chrome instance has launched.
  4. Set a breakpoint on a .ts
  5. Perform the action in the app to trigger the
  6. If all goes well, Chrome will report that the code has been Paused in Visual Studio Code.

Note that this method of debugging doesn’t reliably work. You may have to manually set a breakpoint in Chrome Dev Tools | Sources tab, finding the same .ts file under the webpack://. folder, which will then correctly trigger the breakpoint in VS Code. However, this renders the entire benefit of using VS Code to debug code useless. For more information, follow the Angular CLI section on VS Code Recipes on GitHub at https://github.com/Microsoft/vscode-recipes.

If you liked this article, you can learn more about Angular 6 in Doguhan Uluca’s Angular 6 for Enterprise-Ready Web Applications to follow a hands-on and minimalist approach demonstrating how to design and architect high-quality apps.