Monday, August 22, 2016

How to Use Resolve in Angular 2 Routes



Resolve is a powerful technique to achieve the best user-experience when browsing between pages in your app. It also makes the controller's code much cleaner in contrast to fetching data inside the controller.
Just one tip: do not overuse the resolves
Load only important data in resolves to render main parts of the page immediately and fetch all other data, asynchronously.
Angular1 vs Angular2
In Angular1, we could see the following code to define resolves in router (ui-router):
$stateProvider
  .state('transactions.details', {
    url: '/transactions/:id',
    views: {
      content: {
        controller: 'TransactionCtrl',
        templateUrl: 'transaction.html',
        resolve: {
          transactions: function (Transaction, $stateParams) {
            return Transaction.getById($stateParams.id);
          }
        }
      }
    }
  })
In Angular 2.0.0-rc.4 router, you can do similar stuff but with some key differences:
// main.ts

import { TransactionResolver } from './resolvers/transaction.resolver.ts';

export const routes: RouterConfig = [
  {
    path: 'transactions/:id',
    component: TransactionComponent,
    resolve: {
      transaction: TransactionResolver
    }
  }
];

bootstrap(AppComponent, [
  provideRouter(routes)
])
As you can see, it is pretty much the same except that we pass TransactionResolver class instead of function.
How to implement a Resolver class
Create new folder called resolves and put resolvers with name template<resolveName>.resolver.ts:
// transaction.resolver.ts

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { TransactionService } from '../services/transaction.service';

@Injectable()
export class TransactionResolver implements Resolve<any> {
  constructor(
    private transactionService: TransactionService
  ) {}

  resolve(route: ActivatedRouteSnapshot): Observable<any> {
    return this.transactionService.getById(route.params.id);
  }
}
  • The exported class should be Injectable
  • The class should implements Resolve<any> interface with one methodresolve(): Observable<any>

Why is this example different from Angular 1's docs?

In Angular 2 Docs in Resolve we can see:
class TeamResolver implements Resolve {
  constructor(private backend: Backend) {}
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<any> {
    return this.backend.fetchTeam(this.route.params.id);
  }
}
bootstrap(AppComponent, [
  TeamResolver,
  provideRouter([{
    path: 'team/:id',
    component: TeamCmp,
    resolve: {
      team: TeamResolver
    }
  }])
);
But if you execute this code you will face 2 errors:

  1. Generic type 'Resolve' requires 1 type argument(s).
  1. TypeError: Cannot read property 'params' of undefined.

I can't explain why the interface Resolve requires any argument types, but to make it work just add <any> argument type to Resolve.
resolve() gets 2 arguments while it's executing, but this.route tries to get the property of this class with name route, which is not correct. Just use route.
Still, I don't know why the Documentation is unseemly and uninformative. I spent hours to make resolves work in Angular 2, so hope this article will help somebody.
You can consult some courses in link below:



      Friday, August 19, 2016

      7 Critical Tips to Learn Programming Faster – #3 Will Land You a Job



      Whether you’re currently pursuing a degree in computer science, an aspiring self-taught developer, or a coding boot camp student, mastering the craft of programming is a perpetual struggle. To assist in your learning – courtesy of the Coding Dojo instructors – here are seven tips on how to learn programming faster.

      1.  Learn by doing. Always play with the code while learning

      Learn Programming faster
      With every new subject, the sooner you start playing with the code, the faster you will learn the given concepts. Even if you blaze through an entire chapter of reading and a topic like for loops seems straightforward – so straightforward even a monkey could do it – you’ll still be scratching your head when tasked to implement the code for the first time. You’ll think, “wait, what was that one piece of syntax again?” As the saying goes, you need to “use it or lose it”, because despite the evolution of technology, this ole’ proverb holds true when learning to code.
      Hint: Build a project as you go through the material. A personal project is often the best starting point.

      2. Grasp the fundamentals for long-term benefits

      Learn programming faster 1
      As elementary as they may appear at first, programming fundamentals always need to come first: the better you understand them, the easier it is to learn more advanced concepts. From our experience at Coding Dojo, students who rush through the beginning of our software bootcamp – where our course focuses most on web development fundamentals – are often the first to get stuck as we transition into more advanced material, such as back-end programming. So before you ditch the first class of computer science 101, or skip chapter one of an online tutorial, keep in mind that you are overlooking the most important step in your learning.
       Hint: Read this great article about the 5 Basic Concepts of Any Programming Language

      3. Code by hand. It sharpens proficiency and you’ll need it to get a job

      Learn programming faster
      Computer monitors become thinner, hard drives lighter, and programming languages more powerful, but coding-by-hand still remains one of the most effective methods to learn how to program. Be it on a whiteboard or notebook, coding-by-hand requires further caution, precision, and intent behind every line of code. Because unlike on a computer, you can’t run hand-written code midway through the sheet to check if the work is correct. Although more time consuming, this restriction will mold you into a more fundamentally sound developer, both in the classroom and the job market. For college exams and technical interviews – a critical component of the job interview process – you will have to code-by-hand, because not only is this good for learning, but it’s universally known to be the ultimate test for a programmer’s proficiency. So start early and get used to this old-school practice.

      4. Ask for help. You’ll need it

      Learn programming faster
      As awesome as it would be to become the next Steve Jobs on your own, the reality is that people learn faster with mentors and peer feedback. What may seem like an immovable bug or an unlearnable topic could be quickly alleviated by a fresh pair of eyes or a new interpretation of the subject. Whether it’s online or in-person, ignore the trolls and don’t be afraid to ask for help, because every programmer has been in your shoes before. Besides, most developers love to code, and if there’s one thing that passionate individuals enjoy, it’s to share their knowledge with others.
      Word of Warning: At Coding Dojo we suggest using the 20 minute rule. Take at least 20 minutes to figure something out on your own before asking for help. There’s a good chance that the answer is already in front of you, and besides, struggling makes you a better programmer overall.
      Hint: Stackoverlfow and reddit’s learn programming subreddit are gold mines for online programming assistance.

      5. Seek out more online resources. There’s a wealth of content

      Learn programming faster
      If a particular concept doesn’t make sense, be it on codeacademy, in a textbook, or during class lecture, maintain your confidence and look for alternate online resources to learn the same content. Everyone learns differently, and just because one source doesn’t make sense, doesn’t mean there’s something wrong with you. It means that you’re not clicking with the delivery of the material. The online resources to learn computer programming are endless, and there’s always a reddit post, youtube tutorial, or blog explanation that will make the material-at-hand crystal clear.
      Hint: Don’t underestimate the power of google search.

      6. Don’t just read the sample code. Tinker with it!

      Learn programming faster
      Reading sample code is not enough to understand how it works. To develop a true understanding, you need to actually run the code and tinker with it. With the additions of comments and instructions, sample code is packaged to be easily digestible by the reader; but in realityit’s pretty difficult to replicate from scratch. Reading is not the same as understanding, and actually trying to write the code yourself, or at least running it, will facilitate the learning process much more.

      7. Take breaks when debugging

      Learn programming faster
      When debugging, it’s easy to go down the rabbit hole for hours, and there’s no guarantee that you will fix the problem. To avoid this, it’s best to step away from the bug for a few hours, and return with a fresh perspective. Not only is this a guaranteed way to help solve the problem, but you’ll also save yourself hours of headache. So if help isn’t available – to touch on our previous tip about seeking advice – consider taking a break to clear your mind and return later. In the meantime, the bug won’t be going anywhere, and you’ll at least restore some needed sanity to improve productivity.

      Conclusion: Keep Calm and Keep On Coding

      Despite these 7 tips, the most important ingredient to learn programming faster is to remain confident. To do so, you should expect to fail repeatedly and be patient with your progress; because becoming an expert at anything requires hard work and time. And if a single doubt ever clouds your mind, remember that every programmer has walked this path before – none of them more destined to become a developer than you. Whichever path you are currently on, be it college or coding boot camp, the only barrier to success is your work ethic and confidence to persevere.Read more courses , If you want to master or practice it:

          Monday, August 15, 2016

          Make Your Websites Load Faster with Lazy Loading Images !


          In this post I am going to show you how to make your websites or blogs load faster by using a JQuery plugin created by Luis Almeida called "Unveil".

          Load%2Bwebsite%2Bfaster%2Bberk
          The plugin works by postponing the load of the images that are not visible on the browser. These images are loaded when the user scrolls down and this gives a professional look and improves the performance of the website. Also this technique enables some mobile data users to use less data and prevents unnecessary mobile data charges. 
          First of all let's find the "img" element in our CSS file. It might look like a bit different than mine but it's okay. Then modify it and add the last two statements. 

          
          img {
                  max-width: 100%;
                  height: auto;
                  vertical-align: middle;
                  border: 0;
                  opacity: 0;
                  transition: opacity .5s ease-in;
                }
          
          

          Now all the images on our website are invisible and when the opacity is changed by the Plugin, they will have a transition effect. 
          Alright, the next thing to do is adding the plugin to our website. Find the </body>tag and add the following right before </body>

          
          ....
          ...
          <script type="text/javascript" src="https://yourjavascript.com/16496268113/jquery-unveil.js"></script>
            </body>
          
          

          Finally we need to add the following script to be able to adapt the plugin to our img tags. 
          
          // Created by Berk SOYSAL http://soysal.tk
          $(document).ready(function(){
                
            $("img").each(function() {
              $(this).attr("data-src",$(this).attr("src"));
              $(this).removeAttr("src");
            }); 
          
          
            $("img").unveil(100, function() {
              $(this).load(function() {
                this.style.opacity = 1;
              });
            });
          });
          
          $(window).load(function(){
               $("html,body").trigger("scroll");
          });
          
          

          Warning: Please make sure that the images on your website or their classes have width and height properties. Otherwise your images might not be displayed properly!
          That's all! Now you can test the speed of your website and see the improvement yourself. I am not going to provide a demo page since I am also using this plugin on this website so you have already tested the plugin :)
          Please leave a comment if you have any questions and don't forget to share this with your friends!
          Read more courses at:

          Mastering DockerPython 1000: The Python Primer