Recent Posts

Angular 2 child element attribute not working, use input decorator

When defining a re-usable modal container, I could not get the ‘title’ attribute to appear when set on the parent template’s use of the component.

I was using a modal with a map sibling, as

template: '<div id="map-canvas"></div><modal-container title="Section Notes"></modal-container>'

I figured out the child component needed to use the input decorator on the ‘title’ property. So in modal-container.component.ts, in the export class ModalContainerComponent definition

title: string;

became

@Input() title: string;

and it worked.

See https://angular.io/docs/ts/latest/cookbook/component-communication.html at “Pass data from parent to child with input binding”

Using php with Angular 2 and Laravel

I’ve been using Angular 1.0 for the last few projects, but I wanted to get familiar with Angular 2. I found the process of getting up and running with php a bit annoying.

SUMMARY: With php, you can use the ‘5 Minute Quickstart’ tutorial google offers with some adjustments to asset locations, config paths, node packages, and automated tasks (most notably the typescript transpilation process) to get setup with Laravel and Angular 2. Google uses a node app, and a lite node server. I wanted to avoid this and use php and laravel to deploy assets, etc. and use Angular 2. Conceptually:

  1. Make sure you understand which packages you will need. The best would be just to copy the ones from the Angular 2 google tutorial, though not quite all of them will be used (we will let Laravel handle the typescript transpilation).
  2. Make sure you understand where the hell all the files should go. You need to change google’s root level file structure of the example node app to a php laravel app where public assets reside in the nested ‘public’ folder within the root app. Paths in the files need to be adjusted accordingly.
  3. Make sure you understand how to adjust the automated tasks in the gulp file, and in the laravel-elixir-typescript node package. This is mainly about how to get your typescript files to end up in the right place when they are compiled to javascript.

See https://angular.io/docs/ts/latest/quickstart.html

I’ve tried to explain my experience in a way that will make things easier for someone trying to setup any general php app with angular 2 at any point in the near future. The packages, versions, and syntax of the code may vary in the future, but if you understand what changes you need to make conceptually, it will hopefully be easy to use Google’s tutorials and documentation for the next while. My experience was based on the somewhat murky guide at https://www.codetutorial.io/laravel-5-and-angular-2-beta-setup. The video is at https://www.youtube.com/watch?v=dohhsLSbkYA. I found I needed some clarifications on paths, etc. and that the packages used and versions were outdated or unexplained. I tweaked the tutorial found at https://angular.io/docs/ts/latest/quickstart.html. I was using Laravel 5.2.43. I’ve tried to follow the steps in the google tutorial.

Step 1: Create and configure the Laravel and Angular 2 project

I took a laravel project and figured out where to put all the files from the google Angular 2 tutorial. Some files from the tutorial could just go in the root of the app. The following things need to be adjusted:

a) Create a laravel project, and change into that directory. Mine is called laravel_angular2.

laravel new laravel_angular2
cd laravel_angular2

I’ve gotten used to setting up a virtual host and getting the app and and running with php and apache. Hopefully you’ve already made it to this point.

b) Package definition and config files. Copy the typings.json file into the root of your project. Ignore the tsconfig.json file, as we will use laravel an gulp to handle typescript transpiling and serving the app. Put the systemjs.config.js file in the /public folder of laravel. UPDATE THE PATHS in this file to point to / instead of /node_modules, your public folder. The package.json file needs to be merged with existing laravel one. You can essentially copy the dependencies and devDependencies portions of the tutorial package.json file into the package.json file in the root of your laravel app. You can tweak the packages, perhaps remove the lite server and typescript stuff that google includes. As for me, I just left all the packages google indicated in there. I have yet to figure out a good way to determine, when cloning projects, how the hell to figure out which packages are unnecessary, and how to tell which should just go in the devDependencies section when the list gets real long and full of unfamiliar packages. The scripts and other sections of the tutorial package.json can be ignored since, again, we will use laravel an gulp to handle typescript transpiling and serving the app.

c) Install packages. npm install should work fine. Somehow I always screw the packages up and get error messages, but nothing helpful on how to avoid this comes to mind. Hopefully you only get some warnings. I could not get npm run typings install to work, as per the tutorial. I don’t know if this is because we removed it from the scripts section of the package.json file. You can try adding this section and run the command. I suspect it had more to do with the fact that the console wanted a cli package for typings. Do npm install typings --global to get the global cli package, then typings install. We need to deal with the typings folder and move it into public. I didn’t get errors in my quickstart app without moving the typings folder, but it should be moved to the public folder. So, move the ‘typings’ folder into /public. You could probably use a gulp task command to do this. You could also figure out how the hell to adjust google’s code to put this typings folder in public automatically. I never got to that point. The typings.json config file made no sense to me and I don’t know any of the conventions on using that package. I actually don’t even know what the typings folder is used for, but figured it should go in the public folder.

Ignore the ‘Helpful scripts’ section, as we will use laravel and gulp to run the typescript transpiling and the server.

Steps 2-4: Our first Angular 2 component, etc.

Instead of creating an ‘app’ root folder, make a folder ‘/resources/assets/typescript/app’ to house your typescript files. They will be transpiled to the /public/app folder later. Put all the files mentioned in the tutorial in steps 2-4 there.

Step 5.0: Making sure our Angular 2 typescript transpiles using Laravel and Gulp

I couldn’t get google’s typescript transpiler to work easily, and I wanted to use the one included in the laravel packages. The tricky part about this is to avoid jamming on the javascript into a single app.js file. There are 2 ways I’ve done this. The second way is demonstrated in the tutorial on codetutorial.io (and the youtube video), but it involves modifying a node package in the node_modules folder, which is fragile. In my opinion.

  1. Use the gulp typescript library and make a task for transpiling the javascript from typescript.
    var ts = require('gulp-typescript');
    ...
    gulp.task('typescript', function(){
      var assetPath = './' + elixir.config.assetsPath;
      var search = '/typescript/**';
      var options = {
          // If you use ES5, see http://stackoverflow.com/questions/35660498/angular-2-cant-find-promise-map-set-and-iterator
          "target": "ES6",
          "module": "system",
          "moduleResolution": "node",
          "sourceMap": true,
          "emitDecoratorMetadata": true,
          "experimentalDecorators": true,
          "removeComments": false,
          "noImplicitAny": false,
      };
      var outputFolder = 'public';
      return gulp.src(assetPath + search)
        .pipe(ts(options))
        .pipe(gulp.dest(outputFolder))
    });
    
    ... //in the elixir function
        mix.task('typescript', 'resources/assets/typescript/**'); 
    • This is the weird custom step I found useful. It deals with getting the transpiling to work using the npm package elixir-typescript. This involves tweaking the package code, and will not be committed to the git app as it involves editing the node_modules folder. I don’t know if there is a better way to do this, but this idea comes from the aforementioned tutorial. Add the elixir-transcript package. Version 1.1.2: npm install elixir-typescript@1.1.2 I haven’t added this to the package.json file, as we are editing the package manually, but you could add it. Be aware that on certain npm actions, the required update that makes our transpiling work may be overwritten and break.
    • In the file /node_modules/elixir-typescript/index.js, comment out the concat line. //.pipe(concat(outputFileName)). This was on line 28 for me. This is so that when the typescript files are transpiled, they don’t all get mashed into one app.js file. Angular 2 would not like this. Every time you do npm install, you may have to redo this!
    • add the following to your gulp file. The first line was already there for me:<code>

      var elixir = require('laravel-elixir');
      var elixirTypscript = require('elixir-typescript');
      ...
      elixir(function(mix) {
      mix.typescript('app.js','public/app','/typescript/**/*.ts',{
        // If you use ES5, see http://stackoverflow.com/questions/35660498/angular-2-cant-find-promise-map-set-and-iterator
        "target": "ES6",
        "module": "system",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false,
      });

      Run gulp typescript to make sure it works. There should now be javascript files in /public/app. The paths here are weird and took me some tinkering to figure out. More on this later. These 3 steps were definitely the trickiest part of the whole process. It’s more about if you’re keen on learning how to use typescript with your php projects, as similar steps would probably need to be used in any tool that uses typescript on the frontend.

Step 5

Setup the welcome/index/homepage of your Laravel app to load the Angular 2 app. Instead of making an index.html as per the tutorial, update your home view, or whatever you want to run the angular 2 app, to use the html that is in the tutorial. We will need to modify the url paths since the packages used by Angular 2 reside in node_modules folder, which is not in /public. We also need to copy the used packages into the /public folder so we can reference them from the script tags. We will accomplish this by:

  1. Input the html, etc. from the tutorial. In my /resources/views/welcome.blade.php file I added Loading... in the content div. Copy the script tags from the tutorial into the head section.
  2. Add the following commands to the Laravel gulp file in the elixir function:<code>

    mix.copy('node_modules/core-js', 'public/core-js');
    mix.copy('node_modules/reflect-metadata', 'public/reflect-metadata');
    mix.copy('node_modules/zone.js/dist/zone.js', 'public/zone.js/dist/zone.js');
    mix.copy('node_modules/systemjs', 'public/systemjs');

    The following 3 files are also necessary for the framework.

    mix.copy('node_modules/@angular', 'public/@angular');
    mix.copy('node_modules/angular2-in-memory-web-api', 'public/angular2-in-memory-web-api');
    mix.copy('node_modules/rxjs', 'public/rxjs');
  3. Remove references to node_modules from the script includes in your view file. For example, ‘node_modules/core-js’ should just be ‘core-js’. I edited my /resources/views/welcome.blade.php and removed all the ‘node_modules’ from the script tags. The systemjs.config.js file should already be in the public folder from Step 1. Again, note that you should remove reference to the ‘node_modules’ path in this systemjs.config.js.And with that, run gulp, hit your Laravel app’s url,and the quickstart app should load! You’ll probably want to add a gulp task to monitor changes to your typescript. And this is usually the point in a web post where I’m like ‘What the hell, this isn’t working and you seem to be missing some explanations.’ As I think of them, I’ll try and stay current and add in more explanations and pitfalls to avoid this.

TCP versus unix socket sock connection refused failure for php5 fpm and nginx

[error] 13169#0: *7 connect() failed (111: Connection refused) while connecting to upstream, client: XXX.XXX.XXX.XXX, server: test.local, request: "GET /index.php HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "test.local"

When setting up nginx to work with php-fpm on ubuntu 14.04, this happened when I was using some config templates from a bit older server. It seems to result from nginx being configured to listen with a socket connection versus TCP, and the virtual host being configured to listen with TCP. The fix was somewhat intuitive, but I never would have thought to look in /etc/php5/fpm/pool.d/www.conf.

The fix for me: In /etc/php5/fpm/pool.d/www.conf, change
listen = /var/run/php5-fpm.sock
TO
listen = 127.0.0.1:9000

This should match the php line in your /etc/nginx/sites-enabled/WHATEVERCONFIG. Mine uses TCP with the line
fastcgi_pass 127.0.0.1:9000;
as opposed to
fastcgi_pass unix:/var/run/php5-fpm.sock;

http://stackoverflow.com/questions/15852884/nginx-connect-failed-error

Using postfix on linux for sending only outgoing messages

Summary: What you want is to set up a null client. http://www.postfix.org/faq.html#null_client See my notes below for what constitutes an ’smtp server entry’.

So for my local dev environments I’ve been in the habit of setting up php’s mail function to work by doing a ’sudo apt-get install sendmail’ and editing the php.ini to point the sendmail_path to /usr/sbin/sendmail. (I’d recommend this procedure only if you’re working locally and don’t plan on opening port 25 to anything public, won’t want to mess with domain names, and won’t be dealing with mx records, etc.).

Well when I actually had to setup a server with a public domain, and needed emails to work efficiently from php with a qualified domain while worrying about port 25 being secure, I was in for some fun. For starters I’d recommend postfix over sendmail. Much easier to configure. Sendmail has many more config files, and you have to re-compile some of them after edits, etc. So once you have postfix installed, if you just want to send outgoing emails, then you can increase security and reduce overhead by making postfix not listen on the SMTP port. I wanted postfix as an smtp client only. With sendmail you can do this, and even kill all the daemons. With postfix you still need the daemon going, but when we’re done, nothing will be listening on port 25, smtp.

So what we are setting up is called a ‘null client’. You just have to modify /etc/postfix/main.cf and master/cf according to the instructions at http://www.postfix.org/faq.html#null_client.

The main thing that was unclear to me is what line(s) constitute a ‘SMTP server entry’ in master.cf. After commenting out the line close to the top with ’service’ as ’smtp’ and ‘type’ as ‘inet’, I figured this was enough, as ’sudo lsof -i’ indicated nothing was listening on port 25, or as smtp. I would leave the other smtp service entries alone, the ones with ‘type’ as ‘unix’.

Then do ’sudo postfix reload’ and for good measure we may as well do ’sudo /etc/init.d/postfix restart’, or the equivalent on your linux distro.

git permissions error: unable to create temporary sha1 filename ./objects/19: File exists

I had done a git rm of some swp files (I had forgotten to put *.swp in my .gitignore for this project) and after committing, I pushed to the remote origin and was suprised to see:

error: unable to create temporary sha1 filename ./objects/19: File exists

If you get this error (Where 19 is a number unique to your situation), then it is probably a permissions issue. On the remote server, make sure the remote bare repos, and ALL subfolders and files are owned by the appropriate (usually git) user. What is annoying is that somehow in the course of pretty normal git tasks, a non-git user was assigned ownership, or the git user was denied rights somehow. I forgot to check what the bad permissions were before I chowned and chgrped the files.

Once I logged in as an admin, changed to the git user’s home directory where all the remote bare repos exist, and issued ’sudo chown -R git ./’ and ’sudo chgrp -R git ./’ all was well.

I think the way to avoid this error is to make sure you are using the git user if you are pushing changes on the same server as the remote git repos.

See a more in depth discussion at http://kerneltrap.org/mailarchive/git/2008/11/28/4258264/thread

jQuery checking if a selector worked or is valid

So if a jQuery selector failed to match it used to return the document at the root level of the DOM. Now it will return an empty set. What is an empty set? If you do var test = jQuery(); you’ll get the thing — an empty jQuery wrapper object that appears around every selected element when using jQuery selectors.

So, if you do $(‘#bogusId)’, you should get a jQuery object with a length of zero. I think that is the best way I have seen to tell if nothing was matched, just check for a length of zero on the result of calling something that doesn’t match.

if($(‘#bogusID’).length ==0)

OR

var myjQueryElement = $(‘#bogusID’);
if(myjQueryElement.length == 0 )

You can also use size()

See http://api.jquery.com/jQuery/

‘As of jQuery 1.4, calling the jQuery() method with no arguments returns an empty jQuery set. In previous versions of jQuery, this would return a set containing the document node.’

gem install rails on VirtualBox Ubuntu guest on a Windows 7 host times out

Apparently if you have the network interface as NAT (the most standard one) then the gem installer has issues connecting to remote sources. Use a bridged network connection, or download all the gems you need separately for rails, and install each using the gem install GEMNAME –local command in the folder where you download the gems. (I couldn’t get the bridged connection to work either, so I just installed all the gems by downloading each gem separately. Sort of annoying, but once you know how to do it, and what the dependencies are (rails has sort of a lot, but not too bad), it is easy. Use rubygems.org and not rubyforge.org)

This is weird since other remote gems work fine. The link at the bottom discusses how this might be a bug or something. Very annoying though, getting to the point where you find that it isn’t a linux problem, but a virtualbox and rubygems thing.

To get to the nitty gritty you have to do sudo gem install -V –debug (for verbose debugging).

The first level of error, by using the -V verbose option will show
Error fetching remote data: timed out (on some remote gem), and then eventually the non-verbose error:

ERROR: While executing gem … (Gem::RemoteFetcher::FetchError) timed out (http://rubygems.org/gems/rails-x.x.x.gem)

To get to the root of the problem, you use the –debug flag which will show

Exception `NameError’ at YOURENV/command_manager.rb:161 – uninitialized constant
Gem::Commands::InstallCommand
Exception `Gem::LoadError’ at YOURENV
rubygems.rb:826 – Could not find RubyGem sources (> 0.0.1)
Exception `Errno::ETIMEDOUT’ at YOURENV/net/

See http://www.ruby-forum.com/topic/204146

Installing newer version of rails on ubuntu 9.10 karmic koala

I had a bunch of weird errors, like actionpack requires a certain version of rack, etc. when trying to use the gem install rails and other such commands.

I found it easier to remove any gems that were old, and then just download each gem dependency from rubyforge.org. Then I could download each gem, go to that download folder in the command line, and run sudo gem install GEMNAME – -local, and make sure the versions I wanted for everything were correct

ruby extconf.rb install mysql
extconf.rb:1:in `require’: no such file to load — mkmf (LoadError)
from extconf.rb:1

Make sure the package rubyXX-dev is installed. This will stop the mkmf errors.

ruby extconf.rb install mysql
extconf.rb:1:in `require’: no such file to load — mkmf (LoadError)
from extconf.rb:1

When installing the mysql gem in ubuntu make sure you have the following 3 packages installed: build-essential, rubyXX-dev, and libmysqlclientXX-dev, where the XXs correspond to your version numbers.

If you want to read the log, in ubuntu 9.10 with ruby 1.8.7 and rails 2.3.4 it was in /var/lib/gems/1.8/gems/mysql-2.8.1/ext/mysql_api/mkmf.log

Also be aware that 9.10 ubuntu’s default mysql sock appears to be /var/run/mysqld/mysqld.sock

Ruby on Rails and Flex using rubyamf association errors

I’ll have to re-duplicate the exact error message on ruby’s side. From what I recall, this was obscured by a bunch of weird error messages that were deep in the codebase for rubyamf.

Basically, if your rails server barfs a bunch of errors when you try and load activerecord objects from an amf request, one cause of this can be the fact that you have associations setup in your rubyamf_config.rb file, and there are bad or missing foreign keys in the database for linking associated tables.

In the following example ruby barks when an account is loaded. Account has a location_id in the database to a location. If the location record with that id does not exist, ruby does not throw a nice error.


ClassMappings.register(:actionscript => 'Account', :ruby => 'Account', :type => 'active_record',
    :attributes => ["id", "location_id", "verified", "org_id", "login", "password", "email",  "name_title", "name_first","name_middle",
        "name_last","name_suffix","phone","phone_2","phone_3","last_login_at", "created_at", "updated_at", "business", "residential"],  
    <span style="color:#CC6666">:associations => ["locations"]</span>)