ANGULAR2 Series Tutorials (vi) Upgrade equipment, pipe

Source: Internet
Author: User
Tags export class

Today, we're going to talk about ANGUALR2 's pipe, but we need to upgrade our gear before it's too shabby.

Example

This example contains two pipes, one is stateful, the other is stateless, and is a direct copy of the official example. This example also contains my angularclass/angular2-webpack-starter this awesome starter rewrite, I will explain the configuration in detail.

Source

No test angularclass/ angular2- Webpack-starter

This contains Angular 2 (Router, Http, Forms, Services, Tests, e2e, Dev/prod), Karma, Protractor, Jasmine, Istanbul, Typescrip T, Tslint, typings, and Webpack and other aspects of the content, is called the Hall-level development experience, fast wipe your saliva.

However, considering that many of the domestic students do not have FQ, many packages can not be installed, I deleted all the test related NPM dependencies and configuration files, so that I can ensure that each classmate can successfully install and run the program. In addition, we are now learning-oriented, do not write the test code.

However, it is worth mentioning that writing tests is a good habit and can reduce the bug rate of your program very well.

Typings

After you install the entire dependency, you will install typings dependencies. What's this typings for? Why should we use Typings to install some dependencies? Read this article first!

Using the JavaScript class library in TypeScript

In short, we have to use some JS class library in the typescript, we must declare the file with *.d.ts, for the original JS file and the existing TS Project bridge, and Typings and TSD are to install these declaration files! Otherwise, your program will error! Say what what not define!

Typedoc Typedoc

This is the official website, in short, this is used to give you the TS program to generate documents! You can use the command line to generate: NPM run Doc.

Tslint

Used to check TS errors, commonly known as "go to the hair machine", you can develop a good habit of writing TS code, such as the type and variables must have space between: Value:number.

Webpack Configuration

Here I mainly talk about interface, because Webpack plug-in too many, usage too much, we will directly copy to use, want to know the specific configuration can refer to the official website:

More detailed Webpack configuration reference

    1. The entry file has two, one is src/main.ts, it just injects some dependence, launches the app only!
    2. Two is src/polyfills.ts, this and we in the ANGULAR2 Series tutorial (a) Hello world is the same, but he helped us to write all the import in a file. Don't repeat it here.
    3. Static file entry in Src/assets, we can put our static files in this folder, Webpack will automatically help us move into the service, just visit/assets!
    4. HTML entry in the src/index.html, which contains the Webpack template syntax to write CSS, JS reference, as well as Google Analytics, perfect! Directly with the direct use haha!

The above four places are no need to change! Just take it! If your heart is big enough, you can not even understand the configuration, directly to use! But I still hope we know the reason why!

So where do we write the program? In the Src/app. In this folder, in addition to App.ts can only change can not delete, any other files and folders can be deleted!

How to run:

Development environment: NPM start

Production environment: NPM run Build:prod npm run Server:prod

Stateless pipe

After the equipment upgrade, we started to play pipe. Pipe is the filter in Ng1. Let's look at the built-in pipe first:

    • currency
    • date
    • uppercase
    • json
    • limitTo
    • lowercase
    • async
    • decimal
    • percent

No need to write direct use! Today said too much "direct use" haha!

Pipe is divided into two kinds, one is stateful, one is stateless. Let's start by saying that Stateless,stateless uses pure functions, does not remember any data, and does not bring any side effects. Datepipe is stateless, we will write a calculation of the second side of the pipe bar:

Src/app/stateless/exponential-strength.pipe.ts

Import {Pipe, pipetransform} from ' Angular2/core '; /* * Raise The value exponentially * Takes an exponent argument this defaults to 1. * Usage: *   value | exponentialst Rength:exponent * Example: *   {2 |  EXPONENTIALSTRENGTH:10}} *   formats to:1024*/' Exponentialstrength '}) export class Exponentialstrengthpipe implements Pipetransform {  transform (Value:number, args:string[]): any {     return Math.pow (Value, parseint (Args[0] | | ' 1 ');}  }

It is simple to calculate the value of a certain side,{{2 | exponentialstrength:10}} is 2 of the 10-time side.

Write a template test under:

Src/app/stateless/power-booster.component.ts

Import {Component} from ' Angular2/core './exponential-strength.pipe '; @Component ({  ' Power-booster ',  Template: '          Super Power Boost: {{2 | exponentialstrength:10}}    </p>  ',  pipes: [ Exponentialstrengthpipe]}) Export class Powerbooster {}

Inject pipes: [exponentialstrengthpipe], then use it directly!

Stateful pipe

Let's look at a stateful pipe example:

Src/app/stateful/fetch-json.pipe.ts

DeclarevarFetch;import {Pipe, pipetransform} from' Angular2/core '; @Pipe ({name:' Fetch ', Pure:false}) Export class Fetchjsonpipe implements Pipetransform {private fetchedvalue:any; Private Fetchpromise:promise<any>; Transform (value:string, args:string[]): any {if(! This. Fetchpromise) {       This. fetchpromise =Fetch (value). Then ((result:any)=Result.json ()). Then (Json:any)= This. Fetchedvalue =JSON); }    return  This. Fetchedvalue; }}

We did all of these things:

    1. Set the pure parameter to False
    2. In the member function transform, the fetch request is executed, the result is assigned to This.fetchedvalue = json, and The result is returned
    3. If this. fetchpromise This member variable has already been defined, the member variable is returned directly fetchedvalue

Write a template test under:

Src/app/stateful/hero-list.component.ts

Import {Component} from ' Angular2/core './fetch-json.pipe '; @Component (  {' hero-list ',  Template: '           { {Hero.name}}     </div>    <p>Heroes as json:    {'/assets/heroes.json ' | fetch | JSON}}     </p>  ',  pipes: [Fetchjsonpipe]}) Export class Herolistcomponent {  /* */}

'/assets/heroes.json ' is my own JSON file, placed in the assets, because this is the Webpack static file address.

Results:

Feature interpretation

Stateful Pipes is conceptually similar to classes in object-oriented programming. They can manage the data they transform. A pipe that creates an HTTP request, stores the response and displays the output, is a stateful pipe.

This is the official description of the Statefule pipe. Said to be able to create an HTTP request, store the response, show the output of the pipe is stateful pipe. So stateless pipe can't do these things? I am curious to try to make HTTP requests in the stateless pipe:

var' Angular2/core '; @Pipe ({  ' fetch '}) Export class Fetchjsonpipe  implements Pipetransform {  transform (value:string, args:string[]): Any {    fetch (value)        = Result.json () )        . Then ((json:any)   =  json);}  }

The results will not output anything! It is necessary to use the stateful pipe when we need to use HTTP, or when dealing with asynchrony.

Tutorial source code and directory

If you feel that this blog tutorial has helped you, take a star!

Https://github.com/lewis617/angular2-tutorial

ANGULAR2 Series Tutorials (vi) Upgrade equipment, pipe

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.