Subscribe: Jeffry Houser's Blog
Added By: Feedage Forager Feedage Grade B rated
Language: English
angular  app  canvas  component  create  data  err  function  inside  method  npm err  npm  request  selected  uiselect 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Jeffry Houser's Blog

Jeffry Houser's Blog

Jeffry Houser's Blog

Published: Fri, 20 Jan 2017 18:27:15 -0700

Last Build Date: Tue, 17 Jan 2017 10:00:00 -0700


@types/node is not found in the npm registry

Tue, 17 Jan 2017 10:00:00 -0700

I'm trying to run through the Angular 2 Quickstart with TypeScript. When I try to run the npm install command I am getting a ton of errors like this: npm ERR! 404 Not Found npm ERR! 404 npm ERR! 404 '@types/node' is not in the npm registry. npm ERR! 404 You should bug the author to publish it npm ERR! 404 It was specified as a dependency of 'angular-quickstart' npm ERR! 404 npm ERR! 404 Note that you can also install from a npm ERR! 404 tarball, folder, or http url, or git url. npm ERR! System Windows_NT 6.2.9200 npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli" "install" npm ERR! cwd C:\quickstart npm ERR! node -v v0.10.29 npm ERR! npm -v 1.4.14 npm ERR! code E404 npm ERR! npm ERR! Additional logging details can be found in: npm ERR! C:\quickstart\npm-debug.log npm ERR! not ok code 0 It is very frustrating to jump into something new only to find their quick start documentation does not work. The solution appears to be to update NodeJS and npm. I downloaded a new version of NodeJS from the web site. After it was installed, you can update npm like this: npm install npm@latest -g Check your versioning like this: node -v npm -v This upgrade appears to have solved my issues.

Select a Color -- Build a Color Picker in Angular 2 - Part 3

Tue, 10 Jan 2017 09:00:00 -0700

This section will show you how to run Angular code when the canvas is clicked on. Then it will process the image inside the canvas to determine the color and display the results out to the user. It will display results in two different ways; the first is to output the RGB values of the image. The second will be to display another canvas which is colored based on what we selected. Modify the External Template Open up the external template, canvas.html. We'll make a few changes here. First, add a cross hair cursor to the canvas using CSS. This will let people know the canvas can be clicked on: style="border:1px solid #d3d3d3;cursor: crosshair;" This might be better put in an external CSS file, but for simplicity I defined all styles in-line. The canvas will need to do something when the image is clicked, so add a click event: (click)="pickColor($event)" We'll create the pickColor() method inside our main app's component in the next section. Notice the click event is passed to the pickColor() method. Now, create a section to output the selected color: Selected Color RGBA: {{RGBA}} Your browser does not support the HTML5 canvas tag. The first thing it does is output a variable named RGBA. This includes the red, green, blue, and alpha values that make up the selected the color. We'll create that variable in the pickColor() event method. The second element in the template is a new canvas. This will do nothing but display the selected color of the canvas. Modify the Script Now move to the JavaScript code. All this code will modify the colorpicker-app component. First, we need a hook to get access to the selectedColorCanvas. Modify the queries property of the component: queries : { imageCanvas : new ng.core.ViewChild('imageCanvas'), selectedColorCanvas : new ng.core.ViewChild('selectedColorCanvas') } The imageCanvas was there from previous samples, but the selectedColorCanvas uses the same approach. The selectedColorCanvas variable will be accessible inside the class constructor. Inside the class constructor, create a variable for the selectedColorCanvas context: var selectedColorCanvasContext; Inside the image onload() method, inside the onInit() method, save the selectedColorCanvas 2D context: selectedColorCanvasContext = selectedColorCanvas.getContext('2d'); Also, create a variable to include the RGBA value: this.RGBA = '' This variable is put in the 'this' scope. This is similar to the $scope of an AngularJS 1 application, and using 'this' allows the value to be accessed inside the view template. Now, implement the pickColor() method. Here is the stub: this.pickColor = function(event){ } The event is passed in so we can get the x and y position that was clicked on the image: var data = imageCanvasContext.getImageData(event.layerX, event.layerY, 1, 1).data; This loads all the image data using the getImageData() method on the imageCanvasContext. The values into this method are the x value, the y value, the width, and height. layerX and layerY values from the event object specify the location that was clicked. By specifying 1, 1, for the width and height we get all the information for the single pixel which was clicked. The data object contains an array with four elements, representing the red, green, blue, and alpha properties on the pixel that was clicked. Now, let's draw that color on the selectedColorCanvas: selectedColorCanvasContext.fillStyle = "rgba(" + data[0] + "," + data[1] + "," + data[2] + "," + data[3] + ")" selectedColorCanvasContext.fillRect(0,0,250,250); First the fillStyle is defined, as a string, using the rgba() method along with the RGBA data. Then the fullRect() is called. The fullRect() method accepts four arguments, similar to the getImageData() method. The first two values are the x and y values to start the rectangle. The third and fourth values are the height and width, respectively. Our rectangle draws all over the selected canvas. Finally, set the RGBA value using the[...]

Access an HTML5 Canvas -- Build a Color Picker in Angular 2 - Part 2

Tue, 03 Jan 2017 09:00:00 -0700

This is the second in a series of articles about building a color picker in Angular 2. The previous article focused on building the infrastructure and showing you how to use an external template in an Angular 2 component. This article will focus on creating the canvas, accessing it from Angular, and then using it to load an image. Create Canvas To create the canvas, open up the template, canvas.html. Add a canvas element: Your browser does not support the HTML5 canvas tag. It is that easy. The canvas is named imageCanvas with the id tag. I specified a height and width which is equal to the image we'll use. I also gave the canvas a border. Beyond that, the canvas doesn't do anything yet. Access Canvas in Code Drilling into the HTML template to get a handle on the underlying canvas was harder to figure out than I thought it would be. The answer is to add a queries attribute to the AppComponent: ng.core.Component({ selector: 'colorpicker-app', templateUrl : '03canvas.html', queries : { imageCanvas : new ng.core.ViewChild('imageCanvas'), } }) The queries attribute creates a new viewChild. The name of the child is the same as the id we put to the canvas, so behind the scenes Angular will give us a hook to the HTML element so we can access it inside the class. Load the Image The final step for this article is to load an image into the canvas. I found a colorful creative commons image from Flickr that will do great for our demo. To load an image onto the canvas, we need to get access to the imageCanvasContext, so create a variable for that inside the colorpicker-app's component constructor: .Class({ constructor: function() { var imageCanvasContext; } }); That just creates a variable, let's execute a method on startup: this.onInit = function(){ } this.onInit(); This is a convention I use commonly in my AngularJS 1 applications, and I'm just mimicking it here. I haven't decided if it is a good convention yet, but it works. First, load the image: var myImg = new Image(); myImg.src = 'ColorfulImage.jpg'; Easy enough! When the image has completed loading, we want to add it onto the Canvas. First, add a function for the onload() event of the Image: myImg.onload = function() { } Inside the onload() function, get access to the 2D canvas context: imageCanvasContext = imageCanvas.getContext('2d'); We need access to the context before we can draw on the canvas. Next, draw the image: imageCanvasContext.drawImage(myImg, 0, 0); This uses the drawImage() method on the canvas context. The image is placed at coordinates 0,0. Since we purposely sized the canvas to the size of the image, the image should cover the whole canvas. Run the app: View the app here. Unfortunately, I can't provide a link to a plunker for this sample because cross domain issues would prevent the image from loading. What's Next? The primary purpose of this entry was to show you how to get access to an HTML element inside a component's HTML. The final entry in this series will show you how to interact with the canvas, when it is clicked. Sign up for DotComIt's Monthly Technical Newsletter First Name Email Address * [...]

Use an External Component Template -- Build a Color Picker in Angular 2 - Part 1

Tue, 18 Oct 2016 09:00:00 -0700

This series of blog posts will document documents a quick little prototype I put together for a client. They wanted to be able to click on an image and get information about the color at the selected spot. It makes use of the HTML5 Canvas tag and is the most "Flash-like" thing I've done with HTML. This first in the series will show you how to use an external template to an Angular 2 Component and how to access HTML Elements within that template. Setup the App The first step is to import all the Angular 2 libraries: This loads the Angular library, the uiSelect library, and the angular sanitize library. Angular Sanitize is an Angular library used to parse HTML into Tokens. It is required as part of uiSelect. Some Style sheets are needed too: These are a custom style sheet for the uiSelect directive and the style sheet for Bootstrap. The uiSelect has multiple themes that can apply to it. For the moment, I'm only using the bootstrap theme. All the libraries and CSS sheets are loaded from remote CDNs instead of being hosted locally. Create the Angular Code The next step is to create the Angular code. First, create the Angular module: angular.module('uiSelectTestApp', ['ngSanitize', '']); The uiSelect and ngSantitize directives are passed as configuration arguments into our main module. Next, create a controller: angular.module('uiSelectTestApp').controller('ctrl', ['$scope',function($scope){ $scope.dataProvider = [ {id:1, label:'Alabama'}, {id:2, label:'Alaska'}, . . . {id:50, label:'Wyoming'}, ] }]); The controller is named ctrl. It contains a single $scope variable, which is an array. The array contains a list of US states, and will be used to populate the uiSelect component. That is enough for the JavaScript code. Create the HTML The last step is to add the uiSelect component to the page. First, create the Angular app and controller to the page: This code adds the ngApp attribute on the body tag and the ngController attribute on a div tag inside of it. Inside the div, the uiSelect component is implemented: {{$select.selected.label}} There is lots going on here, so let's dissect it one piece at a time. First the main uiSelect: The main uiSelect component contains an ngModel, which acts just like the ngModel on every other angular component you've used. The theme specifies the theme, in this case I specified it to bootstrap. I'm not going to explore themes in this post, but I hope to do so in more detail later. The last attribute is title, which acts like a tooltip when mousing over the component. Next look at the match: {{$select.selected.label}} The uiSelectMatch directive is used to display a label. If an item is selected in the drop down; it will display to the user. If no item is selected the placeholder will display as a prompt. The $select is a service specific to the uiSelect component. We are using it to drill into the selected object and display its label. The uiSelectChoices is used to populate the items that appear in the drop down: The repeat attribute is a loop. It looks over all the items in the dataProvider--which was defined in the controller's $scope. It applies a filter onto those items; using a default one from the uiSelect's $select directive. The default filter searches for any string typed into the uiSelectMatch entry and restricts the display list as such. The span inside the uiSelectChoices determines what is displayed inside the drop down. For my purposes, I just put the label; but you could expand this to include images or other items. The highlight filter is applied to the label, which will highlight the search items in the filtered drop down. Test The App Try the app. This is the app in its default state: This is the app with nothing typed in: This is the app with some filtering: Final Thoughts I was surpris[...]

Using an Angular HTTP Interceptor

Tue, 11 Oct 2016 09:00:00 -0700

I was working on a client project. Two separate AngularJS applications were using the same set of services. The services were using cookies to keep track of server side session data. A small subset of users used both applications and both applications were hosted on the same domain. Did you guess why this is a problem? For users who used both applications, the services could not tell which application the user was using, as such service requests from one app were sometimes being run based on login privileges of the second. This was causing all sorts of problems. The services team decided the best way to accommodate this was to force an argument onto every service request for one of the applications. The server would use this argument to keep the sessions straight. I don't know all the specifics of how the services were implemented, so can't comment on that. But, I can tell you how we modified the Angular code to address this issue. We used an AngularJS HTTP Intercepter . What is an Interceptor? The purpose of an AngularJS HTTP Interceptor is to modify all HTTP requests performed by AngularJS. Y This will affect all requests including REST operations, loading ngInclude files, or loading directive templates. You can set up an interceptor to modify requests before they are sent to the server. You can use it to modify responses before the response is sent back to the result method. An interceptor can also handle request and response errors. When you need to change every service request the application makes to add a new URL argument, this is a great way to do that. Creating the Interceptor A request interceptor must be created in an Angular config block, so here is a config block: angular.module('testModule').config([''$httpProvider", function($httpProvider){ }]); The $httpProvider service is passed into the config function using Angular's dependency injection syntax. The interceptor must be created on the $httpProvider service; which will affect all http requests coming from the app: $httpProvider.interceptors.push(function(){ return { "request" : function(config){ return config } } } This is a basic request interceptor, which performs no functionality yet. $httpProvider.interceptors is an array; and a function is pushed onto it. The function returns an object, which contains properties for each type of interceptor--request, response, requestError, responseError. In this case I only defined a request interceptor. The value of the request is another function. This function accepts a single argument, config that contains configuration data of the request. Then it returns that configuration object. We have not written code to modify the argument yet, but will next. Modify the HTTP Request How you modify the HTTP Requests depends on what you want to do. For my purposes, I wanted to append a query string argument to the request. Without knowing the nature of the request, I won't know if existing arguments already exist or not. My first order of business is to determine if I need to add a question mark to the URL--to start a query string--or an ampersand to add to an existing query string: var queryStringPrepend = "?"; if('\\?') != -1){ var queryStringPrepend = "&" } This creates an argument named queryStringPrepend. This is the value to place before our special query string variable that must be added to all service calls. I default the argument to a question mark for creating a brand new query string. Then I perform a regex search on the config's url to see if it already contains a question mark or not. If the question mark exists then change the queryStringPrepend value to an ampersand. The next step is to add the query string to the configuration's URL: Config.url += queryStringPRepend + "SpecialVariable=SpecialValue" This uses simple string concatenation. Next return the config argument: return[...]