Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

Archive for JavaScript

April 28, 2016

Angular 2: Getting Started With Visual Studio 2015

My “Angular 2: Getting Started” course on Pluralsight details how to get started with Angular 2. To provide guidance that works on any platform (Windows, OS X, and Linux), the course uses Visual Studio Code as the editor. However, there are many developers that prefer to use Angular 2 with Visual Studio 2015.

The biggest challenge in providing guidance for using Angular 2 with Visual Studio 2015 is that there are too many options.

  • Do we use TypeScript? If so, do we use a TypeScript project in Visual Studio 2015?
  • Do we use a simple “Web Site”?
  • Do we use ASP.NET? If so, ASP.NET version 4.6 (current version) or ASP.NET Core 1.0 (previously known as ASP.NET version 5.0 and currently in beta)
  • Do we use MVC? If so, MVC 5 (current version) or MVC 6 (currently in beta)?
  • Do we use more JavaScript-ish tools such as npm? Or try to do everything with Visual Studio tools?
  • Do we use the command line? Or try to do everything within the Visual Studio 2015 IDE?
  • And so on …

The plan is to cover several of these options, starting with the most basic steps required to use Visual Studio 2015 with Angular 2.

Here are the links to the options covered so far:

Enjoy!

April 4, 2016

“Angular 2: Getting Started” Problem Solver

Filed under: Angular 2,JavaScript @ 12:25 pm
Tags: , ,

This blog post supports the sample code for the “Angular 2: Getting Started” course on Pluralsight, providing common issues along with their solutions. This includes issues migrating to newer releases of Angular 2. The course “as is” supports up to Angular 2 Beta 15.  If using a newer Beta or the release candidate (RC), please see the notes below.

The sample code can be found here: https://github.com/DeborahK/Angular2-GettingStarted. The folders in this repo include:

  • APM – Start: The starter files. Use this as a starting point to code along with the course.
  • APM – Start VS 2015 ASP 4x: The starter files set up for Visual Studio 2015 using an ASP.NET 4.x project. Use this as a starting point to code along with the course using Visual Studio 2015. (NOTE: This won’t exactly match the demos in the course.)
  • APM – Final: The completed files, updated to Angular 2 Beta 15. This code matches with the demos presented in the course.
  • APM – Final Updated: The completed files, updated to Angular 2 RC 4. This code includes breaking changes as noted in this blog post.

Please post to the Discussion tab for the course if you experience an issue not found in this post. Thanks!

Setting Up Behind a Corporate Web Proxy

Problem: The error you may see is: “Unable to read typings for es6-shim” when using `npm install`.

Solution 1: npm may not be using your globally defined proxy setting. Try adding a .typingsrc file with the value: "proxy=http://myproxy.com:myport"

Solution 2: Try manually installing the typings by running the following command at the command prompt: `npm run typings install`

See these posts for more information:

NOTE: If you do not have access to the proxy URL and port, you can install the missing typing manually following the steps posted in the comments for this post below.

 

“My First Component” Never Appears

Problem: After building the app.component and using npm start, the “Loading the app…” appears but the page title and “My First Component” never appears.

Solution: Be sure that the template is surrounded with back ticks (`) NOT a single quote (‘):

template: `
     <div><h1>{ {pageTitle} }</h1>
            <div>My First Component</div>
     </div>
`

 

Failed to Load Resource (favicon.ico)

Problem: The sample application loads and runs fine, but there is an error in the console that states: “Failed to load resource: the server responded with a status of 404 (Not Found)”. The file that is not found is listed as favicon.ico.

image

Solution: No favicon.ico file was provided with the sample application. If desired, add one to the root folder to resolve this 404 error.

 

Currency Pipe Does Not Work

Problem: The Angular 2 Currency pipe does not work in some browsers, such as Safari.

Solution: This is an internationalization issue and there is a work around as follows:

1. Install the international package: npm install intl@1.1.0 –save

2. Include the following in index.html:

  <– International Support –>
  <script src="node_modules/intl/dist/Intl.min.js"></script> 
  <script src="node_modules/intl/locale-data/jsonp/en.js"></script>

[[As provided by Amal Sudama on the discussion board for this course.]]

 

Custom Filter Pipe Has Errors (>= Angular Beta 16)

Problem: The signature of the transform function required to implement a custom pipe was changed in Angular Beta 16. The second argument to the transform method was an array of strings and starting in Beta 16 it is now a variable number of arguments.

The error you may see is: “Property ‘toLocaleLowerCase’ does not exist on type ‘string[]’”. Or you may see other TypeScript type errors.

Solution: Change the transform function from this:

OLD productFilter.pipe.ts

transform(value: IProduct[], args: string[]): IProduct[] {
    let filter: string = args[0] ? args[0].toLocaleLowerCase() : null;
    return filter ? value.filter((product: IProduct) =>
        product.productName.toLocaleLowerCase().indexOf(filter) !== -1) : value;
}

To this:

NEW productFilter.pipe.ts

transform(value: IProduct[], filter: string): IProduct[] {
    filter = filter ? filter.toLocaleLowerCase() : null;
    return filter ? value.filter((product: IProduct) =>
        product.productName.toLocaleLowerCase().indexOf(filter) !== -1) : value;
}

This change is *only* required if you are using Angular Beta 16 or newer.

 

Template Parse Warnings (>= Angular Beta 17)

Problem: There is a warning in the console that states: “Template parse warnings: ‘#’ inside of expressions is deprecated”.

This is due to a change in the *ngFor directive in Angular Beta 17. Instead of a local variable defined with ‘#’, the *ngFor directive uses the ES 2015 ‘let’ keyword. The result is a statement much more similar to the ES 2015 for/of construct.

image

Solution: Change the *ngFor directive syntax to use ‘let’ instead of ‘#’ as follows:

Change this:

OLD product-list.component.html

<tr *ngFor=’#product of products | productFilter:listFilter’>

To this:

NEW product-list.component.html

<tr *ngFor=’let product of products | productFilter:listFilter’>

This change is *only* required if you are using Angular Beta 17 or newer.

 

Cannot find module ‘angular2/core’ (>= Angular RC 0)

Problem: After typing `npm start`, the command window displays multiple errors including: ”Cannot find module ‘angular2/core’. The browser console displays “Failed to load resource: the server responded with a status of 404 (Not Found)” on files including angular2/core.

The first release candidate of Angular 2 repackaged all of Angular into individual packages, one per each feature area. All of the packages are now distributed using the @angular npm scoped package. This changes how Angular is installed via npm and how code is imported.

For the list of all Angular 2 packages, see this link.

This basically means two things:

  1. Many of the starter files have changed.
  2. All of the import statements that import Angular must be changed.

Solution: Here are the steps:

  1. Get the new starter files either from the updated repository for this course or from the Angular 2 Quick Start repository.
  2. Delete the current node-modules and typings folders.
  3. Re-run `npm install`
  4. Change every import statement that imports from an Angular library to use the new scoped package syntax.

Change this:

import { Component } from ‘angular2/core’;

To this:

import { Component } from @angular/core’;

These changes are *only* required if you are using Angular RC 0 or newer.

 

Migrating to the New Component Router (>= Angular RC 3)

Problem: After the move to Angular RC, you may want to migrate to the newest component router.

Solution: The newest component router is significantly different from the prior routers. See the Angular 2 documentation for details: https://angular.io/docs/ts/latest/guide/router.html.

These changes are *only* required if you are using Angular RC 3 or newer.

 

Implementing Product Detail: Undefined Product

Problem: When implementing the product detail page, it generates an undefined exception such as “TypeError: Cannot read property ‘prodcutName’ of undefined”.

Solution: This problem occurs because the view is displayed prior to retrieval of the data. To prevent this error, add the following to the product-detail.component.html file:

<div class=’panel panel-primary’ *ngIf=’product’>

This prevents display of the view until the product is retrieved and populated.

 

Twitter Bootstrap Does Not Work Properly

Problem: If you add component features to the sample application using Twitter Bootstrap, they may not work properly. For example, if you add the Twitter Bootstrap styles to display a dropdown menu, the menu does not drop down.

Solution: To keep the sample application focused on the basics of Angular 2, I only added the Twitter Bootstrap styles, not its components. To use any of the Twitter Bootstrap components (such as a dropdown menu), you need jQuery and the Bootstrap JavaScript library

1. Modify the package.json file to include: "jquery": "2.2.3" (or whichever version you require)

2. Use the following command to update the packages: npm update

3. Include the following in index.html:

  <!–  Support Bootstrap Components –>
  <script src="node_modules\jquery\dist\jquery.min.js"></script>
  <script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>  

[[As provided by Scott Simpson on the discussion board for this course.]]

 

Performance Issues on Older Versions of IE

Problem: You have to support earlier versions of IE and are seeing performance issues.

Solution: Change from using the es6-shim library to the core-js shim library. This involves a change to index.html as shown in the APM – Final Updated folder.

Enjoy!

Why Angular? Why Angular 2?

Filed under: Angular 2,JavaScript @ 10:52 am
Tags: , ,

Why Angular and not some other JavaScript framework? (And there are lots of JavaScript frameworks out there!)

image

· Angular makes our HTML more expressive. It powers up our HTML with features such as if conditions, for loops and local variables.

· Angular has powerful data binding. We can easily display fields from our data model, track changes, and process updates from the user.

· Angular promotes modularity by design. Our applications become a set of building blocks, making it easier to create and reuse content.

· And Angular has built-in support for communication with a back-end service. This makes it easy for our Web applications to integrate with a backend service to get and post data or execute server-side business logic.

No wonder Angular is so very popular with Web developers!

With so many developers already using Angular 1, why do we need an Angular 2?

image

· Angular 2 is built for speed. It has faster initial loads, faster change detection and improved rendering times.

· Angular 2 is modern. It takes advantage of features provided in the latest JavaScript standards and beyond such as classes, modules, and decorators. And it leverages Web Component technologies for building reusable user interface widgets. Yet it supports both green field and legacy browsers: Edge, Chrome, Firefox and Internet Explorer back to IE 9!

· Angular 2 has a simplified API. It has fewer built-in directives to learn, simpler binding, and a lower overall concept count.

· And Angular 2 enhances our productivity to improve our day-to-day workflow by providing a consistent pattern for writing our code.

For more information on Angular 2, check out my “Angular 2: Getting Started” course from Pluralsight.

Angular 2: Getting Started

Filed under: Angular 2,JavaScript @ 10:43 am
Tags: , ,

Whether you are new to Angular or new to Angular 2, you’re going to want to come up to speed quickly with Angular 2’s components, templates, and services. My latest Pluralsight course “Angular 2: Getting Started” provides the basics you need to get started building an Angular 2 application.

image

The course covers the following topics:

image

o We start with first things first. We’ll select a language and editor to use. Then walk through how to set up an Angular 2 application.

o Next we’ll dive into components. We’ll build the App component using a simple template and minimal component code and metadata. Here the focus is on the code including the what, why, and how.

o We’ll see how to build the user interface for our application using templates, interpolation, and directives.

o We’ll power up that user interface with data binding and nicely format our data with pipes.

o Next we’ll tackle some additional component techniques. We’ll define interfaces, encapsulate styles, and leverage lifecycle hooks to build better components.

o We’ll see how to build a component designed to be nested within other components. And how to communicate between the nested component and its container.

o We often have logic or data that is needed across components. We’ll learn how to build services specifically for this purpose and use dependency injection to inject those services into the components that need them.

o Most Web applications need to communicate with a back-end server to get or post data and to execute back-end business logic. In this module, we’ll leverage http and observables to retrieve the data for our application.

o Our sample application displays multiple views. We’ll see how to set up routing to navigate between those views.

We’re covering a lot of territory. And by the end of our journey, we’ll have a simple, but fully operational Angular 2 application that you can use as a reference for your own development.

Enjoy!

April 30, 2015

What Developers are Saying About: "Angular Front to Back With Web API"

It is sometimes difficult to find detailed step-by-step guidance for building an application using Angular and ASP.NET Web API. The Pluralsight course: “Angular Front to Back With Web API” covers the following topics from front to back:

  • Retrieving Data
  • CORS and Formatters
  • Passing Parameters
  • Using OData Queries
  • Saving Data
  • Action Results, Error Handling & Validation
  • User Authentication & Authorization

(If you don’t have a Pluralsight membership, sign up for a free trial here.)

Here are some of the comments about the course from Twitter and the course discussion page:

Awesome WebAPI + Angular course!

Thanks for your great course, it helped me to understand how to establish different CURD action between front end and back end.

oh yea! Your course rocks too! Even a beginner can view this course and your other one and be successful.

Great course, it is really concise and to-the-point.

First of all I would like to congratulate you on publishing a fantastic set of courses on AngularJS Line of Business Apps and more so recently Angular Front to Back with Web API. I think what stands out for me is the way in which you provide holistic approach to delivering excellent technical content.

I Love your angularjs pluralsight courses. Learnt a lot and using at work.

Your classes on AngularJS on pluralsight is my reason am better than my peers, thanks

Thank you for building a .Net course F2B that uses (vm = this) and (controller as) syntax!!! You rock.

ScreenShot

Enjoy!

June 18, 2014

JavaScript Function Terminology

Filed under: JavaScript @ 12:43 pm

I have been working on and off with JavaScript since 2001. But its one thing to use JavaScript functions and another thing entirely to know the vocabulary of JavaScript functions.

So here are some common JavaScript function terms:

Function Declaration

Defines a named function.

function onClick(buttonName) {

    return “Clicked: ” + buttonName;

}

Calling:

  • onClick() – executes the function and returns the value.
  • onClick – references the function.

In JavaScript, function declarations are always moved (“hoisted“) to the top of their scope at runtime. This means that the function does not need to be declared before it is used.

So something like this is valid:

onClick(“OK”);

function onClick(buttonName) {

    return “Clicked: ” + buttonName;

}

Function Expression

Defines a function as part of a larger expression such as a variable assignment.

The function can be named, as with the onClick function below:

var buttonClick = function onClick(buttonName) {

    return “Clicked: ” + buttonName;

}

Or anonymous as with this function:

var buttonClick = function(buttonName) {

    return “Clicked: ” + buttonName;

}

Calling:

  • buttonClick() – executes the function and returns the value.
  • buttonClick – references the function.
  • onClick() – generates an undefined error.

Function expressions are not “hoisted”. So attempting to use them before they are defined generates a type error:

buttonClick(“OK”);

var buttonClick = function(buttonName) {

    return “Clicked: ” + buttonName;

}

NOTE: The variable declaration (buttonClick) does get hoisted, but only the definition, not the assignment. So at runtime, var buttonClick = undefined is hoisted. But the assignment does not occur until the un-hoisted assignment statement is executed.

Function Statement

Basically a function declaration. (See above).

Guidance

In general, guidance says to favor function expressions over function declarations (or function statements) for the following reasons:

  • The hoisting of function declarations can cause confusion or hard to find bugs.
  • Function expressions more clearly imply that the function itself is an object.

See this link for more examples and an enhanced discussion of function declarations vs function expressions.

Enjoy!

September 24, 2012

Building a JavaScript Client for a Web API Service

Filed under: ASP.NET,ASP.NET Web API,C#,JavaScript,VB.NET @ 12:54 am

An ASP.NET Web API service provides support for many different types of client applications. One such client is a JavaScript application. This post provides a very simple JavaScript client you can use to test your Web API service.

[See this prior post for an introduction to building an ASP.NET Web API service. The service created in that post is the example service used here.]

Here is the HTML/JavaScript code to display all of the key/value pairs for a single object returned by a Web API service.

<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Customer Information</title>
<script src=”../../Scripts/jquery-1.7.1.min.js”
type=”text/javascript”></script>
<script type=”text/javascript”>
$(document).ready(function () {
// Send an AJAX request for Customer Info
$.getJSON(“api/customer/2”,
function (data) {
// On success, ‘data’ contains the customer details.
$.each(data, function (key, val) {
// Format the text to display.
var str = key + ‘: ‘ + val;

                    // Add a paragraph for each property.
$(‘#info’).append(‘<p>’ + str + ‘</p>’);
})
})

             // Handle a fail
.fail(
function (jqXHR, textStatus, err) {
$(‘#info’).html(‘Error: ‘ + err);
});
});
</script>
</head>

<body>
<div>
<h1>Customer Account Information</h1>
<p id=’info’ />
</div>
</body>

</html>

If you followed the prior post mentioned above and built the sample Web API service, you can delete all of the code from the Index.cshtml file and replace it with the above code.

When you run the application, you get this:

image

Let’s go through the JQuery script code. The example uses the 1.7.1 version of JQuery. The script itself does the following:

  • $.getJSON: Gets the JSON format of the data returned when passing “api/customer/2” to the Web API service. You can change the url string passed to the service to match any url accepted by your service.
  • $.each: Iterates over each object, executing a function for each one. In this case, it processes each name/value pair provided by the JSON format.
    • It builds a string with the name of the field, a colon, and the value.
    • It adds the string to a paragraph element and then appends the paragraph to an element with an Id of #info.
  • .fail: Provides error information if an error is returned by the service.

The HTML code displays the header and a paragraph placeholder that is extended by the script.

If you want to display a set of business objects with their name/value pairs, you can change the script as follows:

<script type=”text/javascript”>
$(document).ready(function () {
// Send an AJAX request for Customer Info
$.getJSON(“api/customer”,
function (data) {
// On success, ‘data’ contains the customers details.
$.each(data, function (key, row) {

                $(‘#info’).append(‘<p>’ + ‘Item: ‘ + key + ‘</p>’);
// Process each customer (“row”)
$.each(row, function (rowKey, rowValue) {

                    // Format the text to display.
var str = rowKey + ‘: ‘ + rowValue;

                    // Add a paragraph for each property.
$(‘#info’).append(‘<p style=”text-indent: 5em;”>’
+ str + ‘</p>’);
})
})
})

         // Handle a fail
.fail(
function (jqXHR, textStatus, err) {
$(‘#info’).html(‘Error: ‘ + err);
});
});
</script>

This script includes two .each methods, the first one processes each customer and the second one processes each field of the customer from the JSON.

The result of this script is shown below:

image

Notice that both scripts could be used for any set of JSON objects returned from a Web API service. You just need to change the url string as appropriate for the service.

Enjoy!

© 2016 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs