码迷,mamicode.com
首页 > 其他好文 > 详细

[Angular] Increasing Performance by using Pipe

时间:2018-05-03 22:01:10      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:import   else   anything   ref   points   when   imp   not   example   

For example you make a function to get rating;

getRating(score: number): string {
    let rating: string;
    console.count(‘RatingPipe‘);
    if(score > 249000){
      rating = "Daniel Boone";
    }
    else if(score > 200000){
      rating = "Trail Guide";
    }
    else if(score > 150000){
      rating = "Adventurer";
    }
    else if(score > 100000){
      rating = "Pioneer";
    }
    else if(score > 50000){
      rating = "Greenhorn";
    }
    else{
      rating = "Buzzard food";
    }
    return rating;
  }

Then using it in html:

{{getRating(entry.points)}}

 

These code actually casues the preformance issues, because everything Angualr‘s change detection run, it saw function call inside {{}}, it have to run it everything when anything changes, there is no way to figure out whether the function output changes or not without running it.

 

The way to fix it is using Pipe. Angular will remember the input value and cache the output. Therefore by using pipe we can reduce the number of function call way better.

import { Pipe, PipeTransform } from ‘@angular/core‘;

@Pipe({
  name: ‘Rating‘
})
export class ScoreRatingPipe implements PipeTransform {

  transform(score: number): string {
    let rating: string;
    console.count(‘RatingPipe‘);
    if(score > 249000){
      rating = "Daniel Boone";
    }
    else if(score > 200000){
      rating = "Trail Guide";
    }
    else if(score > 150000){
      rating = "Adventurer";
    }
    else if(score > 100000){
      rating = "Pioneer";
    }
    else if(score > 50000){
      rating = "Greenhorn";
    }
    else{
      rating = "Buzzard food";
    }
    return rating;
  }

}
{{entry.points | Rating }}

 

[Angular] Increasing Performance by using Pipe

标签:import   else   anything   ref   points   when   imp   not   example   

原文地址:https://www.cnblogs.com/Answer1215/p/8987388.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!