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. This post shows you how.

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 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.

Using a Visual Studio 2015 TypeScript Project

For this first technique, we’ll cover how to set up and run the “Angular 2: Getting Started” files using a TypeScript project in Visual Studio 2015.

1. Download the starter files from my GitHub repo: https://github.com/DeborahK/Angular2-GettingStarted

    If you are not familiar with using GitHub, just click on the “Download ZIP” button as shown below. Then unzip the files.

image

2. Open Visual Studio 2015 and create a new project: File | New | Project.

3. Select the TypeScript project template and name the project “APM” for Acme Product Management.

image

4. This creates several TypeScript sample files. Delete app.css, app.ts, and index.html.

image

5. In file explorer, open the cloned or unzipped `APM – Start` folder if you want to start with the project starter files. Open the `APM – Final` folder if you want to work with the final files from the course.

image

image

6. Copy all of the files from within the folder shown above (except the .vscode folder) to the APM project file you just created with Visual Studio.

image

7. Click the “Show All Files” button in the toolbar of Solution Explorer.

image

8. Select to include the api and app folders and the index.html, package.json, tsconfig.json, and typings.json files into the project. If desired, click “Show All Files” again to hide the remaining files.

image

9. Right-click on the package.json file and select: Restore Packages

image

10. Open the Output window (View | Output) to watch Visual Studio 2015 run npm and install Angular 2 and its dependencies.

So even through we are using a Visual Studio 2015 menu option (Restore Packages), Visual Studio is running the Node Package Manager (npm) to install all of the packages defined in the package.json file.

image

11. If npm finishes successfully, it should appear like this (see below) in the Output window.

image

12. Right-click on index.html and select Set As Start Page.

image

13. Press F5 to run and the application appears in the selected browser.

HOWEVER … you won’t be able to edit and continue. And if you edit and try to refresh the browser, you will most likely see a 404 message.

I have not yet figured out the magic required to provide edit and continue using Visual Studio 2015 directly … but you can get edit and continue if you stop debugging and run the application using a script instead of F5 following these additional steps:

14. Display the Package Manager Console (View | Other Windows | Package Manager Console).

15. Type `cd APM` in the Package Manager Console to change to the directory containing the APM project.

NOTE that if you used a different directory name for your project, type that instead. And if you have a space in the name, it will need to be enclosed in quotes: cd “APM – Start”

16. Type ‘npm start’ into the Package Manager Console.

This will launch your default browser and watch for changes. You can then edit any of the project files (AND SAVE!). The browser will then update automatically and reflect your changes.

By following the above steps, you can follow along with the course using Visual Studio 2015 instead of VS Code. Just be sure to follow steps 14-16 above each time you reopen the project to restart the script that watches for changes and refreshes the browser.

It would be great to hear from you on whether these steps worked for you. Follow me on twitter: @deborahkurata

Enjoy!

April 4, 2016

“Angular 2: Getting Started” Problem Solver

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

This blog post is for tracking issues people have had with the sample code for the “Angular 2: Getting Started” course on Pluralsight, along with their solutions. Please check this post if you experience any issues with the sample code and 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: npm may not be using your globally defined proxy setting. Try adding a .typingsrc file with the value: "proxy=http://myproxy.com:myport"

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>
`

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 on the discussion board for this course.]]

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.]]

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

Featuring WPMU Bloglist Widget by YD WordPress Developer