2017-07-15 80 views
1

是否有可能避免銷燬moduleRef並將其用於下一個請求(如在瀏覽器中工作)?應用程序花費太多時間來重新填充存儲(API請求),所以我找到可能性來緩存它。角度通用破壞moduleref

這裏是源代碼從ngx-universal/express-engine

function handleModuleRef(moduleRef: NgModuleRef<{}>, callback: Function, req, res) { 
    const state = moduleRef.injector.get(PlatformState); 
    const appRef = moduleRef.injector.get(ApplicationRef); 

    appRef.tick(); 
    appRef.isStable 
     .filter((isStable: boolean) => isStable) 
     .first() 
     .subscribe((stable) => { 
      const bootstrap = moduleRef.instance['ngOnBootstrap']; 
      bootstrap && bootstrap(); 

      if (!res || !res.finished) callback(null, state.renderToString()); 
      moduleRef.destroy(); // remove this line and avoid creating new instance of NgModuleRef every request 
     }); 
} 
+0

如果刪除該行,會發生什麼情況? –

+0

它會從第一個請求中推送呈現的html,並且在第一次請求之後還保存moduleRef –

回答

0

調試幫助我理解它是如何工作的,我是執行這樣的代碼:

function handleModuleRef(moduleRef: NgModuleRef<{}>, callback: Function, req, res) { 
    const state = moduleRef.injector.get(PlatformState); 
    const appRef = moduleRef.injector.get(ApplicationRef); 
    const router = appRef.components[0].instance.router; 
    const zone = appRef.components[0].instance.zone; 
    zone.run(() => { 
     router.navigateByUrl(req.originalUrl); 
    }); 
    appRef.isStable 
     .filter((isStable: boolean) => isStable) 
     .first() 
     .subscribe((stable) => { 
      const bootstrap = moduleRef.instance['ngOnBootstrap']; 
      bootstrap && bootstrap(); 

      if (!res || !res.finished) callback(null, state.renderToString()); 
     }); 
} 

我們需要在主注入路由器和NgZone自舉組件

當我們進入「handleModuleRe f「我們需要通過將新的導航網址推送到路由器來使啓動」changeDetector「的應用程序不穩定(isStable = false)。但是如果你知道「isStable」是區域屬性(每個應用程序一個屬性),並且技巧是在「zone.run(...)」內調用「router.navigateByUrl」來使區域不穩定。 1)應用程序處理新路線 2)區域不穩定本身 3)等到它會穩定(區域內沒有任何任務) 4)渲染 5)利潤!

結果:通過在存儲器中緩存的所有應用程序,並避免爲每個請求

  • 內存泄漏是可能的(自舉在2-3-4倍

    • 渲染加速應用程序在開始搬運工,它會重啓如果意外掉落)
    • 連續使用狀態