溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么使用管道提高Angular應(yīng)用程序的性能

發(fā)布時間:2021-07-08 11:36:54 來源:億速云 閱讀:126 作者:小新 欄目:web開發(fā)

這篇文章主要介紹怎么使用管道提高Angular應(yīng)用程序的性能,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!

我們通過一個例子來演示下:

Example

@Component({
  selector: 'my-app',
  template: `
    <p *ngFor="let user of users">
      {{ user.name }}有一只貓 {{ getCat(user.id).name }}
    </p>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  users = [{ id: 1, name: 'wang' }, { id: 2, name: 'li' }];
  cats = [{ name: 'Tom', userId: 1 }, { name: 'Jerry', userId: 2 }];

  getCat(userId: number) {
    console.log('User', userId);
    return this.cats.find(c => c.userId === userId);
  }
}

有兩組數(shù)據(jù)分別是 userscats,可以把 users 理解為傳入數(shù)據(jù),或者是其他數(shù)據(jù)源。通過 getCat() 方法獲取對應(yīng)的 貓咪,這種場景再業(yè)務(wù)開發(fā)中再熟悉不過。 最后添加全局模板直接進(jìn)行一個循環(huán)輸出?!鞠嚓P(guān)教程推薦:《angular教程》】

接下來看下輸出

User 1
User 2
User 1
User 2
User 1
User 2
User 1
User 2

可以 getCat() 方法調(diào)用了 8 次,有 6 次無用調(diào)用。這是因為當(dāng)在模板內(nèi)使用方法時,angular 每次變更檢測都會調(diào)用其方法。

我們可以添加一個監(jiān)聽事件

@HostListener('click')
clicked() { }

每當(dāng)點擊事件觸發(fā),就會調(diào)用 4

User 1
User 2
User 1
User 2

這不是我想要,我只想讓它調(diào)用兩次?。。?!數(shù)據(jù)量大了這么玩頂不住。


Pure Pipe

接下來就是主角登場了。我們先創(chuàng)建一個 pipe

@Pipe({
  name: 'cat',
})
export class CatPipe implements PipeTransform {
  constructor(private appComponent: AppComponent) {}

  transform(value, property: 'name' | 'userId'): unknown {
    console.log('User', value);
    const cat = this.appComponent.cats.find(c => c.userId === value);
    if (cat) {
      return cat[property];
    }
  }
}

可以看到 pipe 的實現(xiàn)與之前調(diào)用的方法基本是一樣的,在模板中添加引用之后,卻發(fā)現(xiàn)結(jié)果符合之前的預(yù)期了,只調(diào)用了兩次。

這是因為 pipe 默認(rèn)是 pure pipe,且 Pipe 裝飾器有 pure 可用來設(shè)置管道模式。

@Pipe({
  name: 'cat',
  pure: true
})

pure 表示的是: transform 的值(入?yún)alue)發(fā)生變化時是否 不跟隨變更檢測調(diào)用。

官方解釋:如果該管道具有內(nèi)部狀態(tài)(也就是說,其結(jié)果會依賴內(nèi)部狀態(tài),而不僅僅依賴參數(shù)),就要把 pure 設(shè)置為 false。 這種情況下,該管道會在每個變更檢測周期中都被調(diào)用一次 —— 即使其參數(shù)沒有發(fā)生任何變化。 When true, the pipe is pure, meaning that the transform() method is invoked only when its input arguments change. Pipes are pure by default.

當(dāng)把 pure 改成 false,會隨變更檢測調(diào)用多次,不管值發(fā)生變化沒。

了解變更檢測機(jī)制:

[譯]深入理解Angular onPush變更檢測策略

https://zhuanlan.zhihu.com/p/96486260

這樣我們通過 pipe 代替模板中的方法,就減少了 angular 模板中不必要的調(diào)用。

以上是“怎么使用管道提高Angular應(yīng)用程序的性能”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI