首页 > 其他 > 详细

[Angular] Increasing Performance by using Pipe

时间:2018-05-03 21:47:33      阅读:177      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!