Angular?服務器端渲染應用常見的內存泄漏問題小結
考慮如下的 Angular 代碼:
import { Injectable, NgZone } from "@angular/core";
import { interval } from "rxjs";
@Injectable()
export class LocationService {
constructor(ngZone: NgZone) {
ngZone.runOutsideAngular(() => interval(1000).subscribe(() => {
...
}));
}
}這段代碼不會影響應用程序的穩(wěn)定性,但是如果應用程序在服務器上被銷毀,傳遞給訂閱的回調將繼續(xù)被調用。 服務器上應用程序的每次啟動都會以 interval 的形式留下一個 artifact.
這是一個潛在的內存泄漏點。
這個內存泄漏風險可以通過使用 ngOnDestoroy 鉤子解決。這個鉤子適用于 Component 和 service. 我們需要保存 interval 返回的訂閱(subscription),并在服務被銷毀時終止它。
退訂 subscription 的技巧有很多,下面是一個例子:
import { Injectable, NgZone, OnDestroy } from "@angular/core";
import { interval, Subscription } from "rxjs";
@Injectable()
export class LocationService implements OnDestroy {
private subscription: Subscription;
constructor(ngZone: NgZone) {
this.subscription = ngZone.runOutsideAngular(() =>
interval(1000).subscribe(() => {})
);
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}
屏幕閃爍問題
用戶的瀏覽器顯示從服務器渲染并返回的頁面,一瞬間出現白屏,閃爍片刻,然后應用程序開始運行,看起來一切正常。出現閃爍的原因,在于 Angular 不知道如何重用它在服務器上成功渲染的內容。在客戶端環(huán)境中,它從根元素中 strip 所有 HTML 并重新開始繪制。
閃爍問題可以抽象成如下步驟:
關于正在發(fā)生的事情的一個非常簡化的解釋:
(1) 用戶訪問應用程序(或刷新)
(2) 服務器在服務器中構建html
(3) 它被發(fā)送到用戶的瀏覽器端
(4) Angular 重新創(chuàng)建 應用程序(就好像它是一個常規(guī)的非 Angular Universal 程序)
(5) 當上述四個步驟發(fā)生時,用戶會看到一個 blink 即閃爍的屏幕。
代碼如下:
// You can see this by adding:
// You should see a console log in the server
// `Running on the server with appId=my-app-id`
// and then you'll see in the browser console something like
// `Running on the browser with appId=my-app-id`
export class AppModule {
constructor(
@Inject(PLATFORM_ID) private platformId: Object,
@Inject(APP_ID) private appId: string) {
const platform = isPlatformBrowser(this.platformId) ?
'in the browser' : 'on the server';
console.log(`Running ${platform} with appId=${this.appId}`);
}
}無法通過 API 的方式終止渲染
什么時候需要人為干預的方式終止一個服務器端渲染?
始終明確一點,渲染應用程序的時間點發(fā)生在應用程序 applicationRef.isStable 返回 true 時,參考下列代碼:
function _render<T>(
platform: PlatformRef, moduleRefPromise: Promise<NgModuleRef<T>>): Promise<string> {
return moduleRefPromise.then((moduleRef) => {
const transitionId = moduleRef.injector.get(?TRANSITION_ID, null);
if (!transitionId) {
throw new Error(
`renderModule[Factory]() requires the use of BrowserModule.withServerTransition() to ensure
the server-rendered app can be properly bootstrapped into a client app.`);
}
const applicationRef: ApplicationRef = moduleRef.injector.get(ApplicationRef);
return applicationRef.isStable.pipe((first((isStable: boolean) => isStable)))
.toPromise()
.then(() => {
const platformState = platform.injector.get(PlatformState);
...到此這篇關于Angular 服務器端渲染應用一個常見的內存泄漏問題的文章就介紹到這了,更多相關Angular內存泄漏內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
AngularJs 利用百度地圖API 定位當前位置 獲取地址信息
本文主要介紹了AngularJs 利用百度地圖API 定位當前位置 獲取地址信息的方法步驟。具有一定的參考價值,下面跟著小編一起來看下吧2017-01-01
如何使用AngularJs打造權限管理系統(tǒng)【簡易型】
這篇文章主要介紹了使用AngularJs打造權限管理系統(tǒng)【簡易型】的相關資料,需要的朋友可以參考下2016-05-05

