Angular SSR-无法读取未定义的属性(读取' usubscribe')

发布于 2025-01-19 04:26:15 字数 4884 浏览 0 评论 0原文

我只是出于 SEO 目的将我的 Angular Web 应用程序转换为 ssr。我成功地纠正了主要问题,但最后一个我不知道如何处理。

我有一个带有主体的服务 sqs.service.ts

import { Injectable, OnInit } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
import { Router } from '@angular/router';
import {SNSClient, PublishCommand, MessageAttributeValue} from "@aws-sdk/client-sns";

import { interval, Subscription } from 'rxjs';
import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity";
import { fromCognitoIdentityPool }  from "@aws-sdk/credential-provider-cognito-identity";
import {environment} from "../../../../../../environments/environment";
import {AuthService} from "../../../../../modules/auth";


export interface SnsNotificationMessage {
  Message: string;
  TopicArn: string;
  MessageAttributes: { [key: string]: MessageAttributeValue; }
}

@Injectable({ providedIn: 'root' })
export class SqsService {

  // Set the AWS Region
  REGION = "eu-west-3";
  subscription: Subscription;
  // Set the parameters
  mnotificationTopicArn = environment.MNOTIFICATION_TOPIC_ARN;



  constructor(
    private cookieService: CookieService,
    private router: Router,
    private authentService: AuthService,
  ) {


  }




  ngOnDestroy() {
    this.subscription.unsubscribe();
  }


  /**
   * Send notification to mnotification
   * @param params
   */
  sendNotification(params: SnsNotificationMessage) {

    const idToken = this.cookieService.get(this.authentService.GARA_WEB_USER_JWT_ID_TOKEN_COOKIE);
    // create sns client
    const snsClient = new SNSClient({
      region: this.REGION,
      credentials: fromCognitoIdentityPool({
        client: new CognitoIdentityClient({region: this.REGION}),
        identityPoolId: environment.identityPoolId,
        logins: {
          [environment.cognitoPoolId]: idToken   // 'COGNITO_ID' has the format 'cognito-idp.REGION.amazonaws.com/COGNITO_USER_POOL_ID'
        },
      })
    });

    const run = async () => {
      try {
        const data = await snsClient.send(new PublishCommand(params));
        console.log("Success.",  data);
        return data; // For unit tests.
      } catch (err) {
        console.log("Error", err.stack);
      }
    };
    run();
  }

}

每次刷新应用程序的页面时,我都会收到错误

TypeError: Cannot read properties of undefined (reading 'unsubscribe')
    at SqsService.ngOnDestroy (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\27.js:49:23)
    at C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:58964:55
    at Set.forEach (<anonymous>)
    at R3Injector.destroy (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:58964:28)
    at NgModuleRef$1.destroy (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:73080:41)
    at C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:77106:56
    at Array.forEach (<anonymous>)
    at PlatformRef.destroy (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:77106:31)
    at complete (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:93213:26)
    at C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:93217:24

当我删除或注释下面的代码时,我可以成功重新加载页面,

  ngOnDestroy() {
    //this.subscription.unsubscribe();
  }

但我在代码中遇到了这个新错误

ERROR NetworkError
    at XMLHttpRequest.send (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:521132:19)
    at Observable._subscribe (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:13619:17)
    at Observable._trySubscribe (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:504773:25)
    at Observable.subscribe (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:504759:22)
    at scheduleTask (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:92458:32)
    at Observable._subscribe (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:92496:13)
    at Observable._trySubscribe (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:504773:25)
    at Observable.subscribe (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:504759:22)
    at innerSubscribe (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:505776:23)
    at MergeMapSubscriber._innerSub (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:510200:98)

请问我该如何纠正它? 没有 ssr 它就可以完美工作。问题的原因是什么?提前致谢。

I just convert my angular web app to ssr for SEO purposes. I succeeded to correct main issues, but this last one i don't know how to deal with.

I have a service sqs.service.ts with the body

import { Injectable, OnInit } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
import { Router } from '@angular/router';
import {SNSClient, PublishCommand, MessageAttributeValue} from "@aws-sdk/client-sns";

import { interval, Subscription } from 'rxjs';
import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity";
import { fromCognitoIdentityPool }  from "@aws-sdk/credential-provider-cognito-identity";
import {environment} from "../../../../../../environments/environment";
import {AuthService} from "../../../../../modules/auth";


export interface SnsNotificationMessage {
  Message: string;
  TopicArn: string;
  MessageAttributes: { [key: string]: MessageAttributeValue; }
}

@Injectable({ providedIn: 'root' })
export class SqsService {

  // Set the AWS Region
  REGION = "eu-west-3";
  subscription: Subscription;
  // Set the parameters
  mnotificationTopicArn = environment.MNOTIFICATION_TOPIC_ARN;



  constructor(
    private cookieService: CookieService,
    private router: Router,
    private authentService: AuthService,
  ) {


  }




  ngOnDestroy() {
    this.subscription.unsubscribe();
  }


  /**
   * Send notification to mnotification
   * @param params
   */
  sendNotification(params: SnsNotificationMessage) {

    const idToken = this.cookieService.get(this.authentService.GARA_WEB_USER_JWT_ID_TOKEN_COOKIE);
    // create sns client
    const snsClient = new SNSClient({
      region: this.REGION,
      credentials: fromCognitoIdentityPool({
        client: new CognitoIdentityClient({region: this.REGION}),
        identityPoolId: environment.identityPoolId,
        logins: {
          [environment.cognitoPoolId]: idToken   // 'COGNITO_ID' has the format 'cognito-idp.REGION.amazonaws.com/COGNITO_USER_POOL_ID'
        },
      })
    });

    const run = async () => {
      try {
        const data = await snsClient.send(new PublishCommand(params));
        console.log("Success.",  data);
        return data; // For unit tests.
      } catch (err) {
        console.log("Error", err.stack);
      }
    };
    run();
  }

}

Each time i refresh a page of my app, I got the error

TypeError: Cannot read properties of undefined (reading 'unsubscribe')
    at SqsService.ngOnDestroy (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\27.js:49:23)
    at C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:58964:55
    at Set.forEach (<anonymous>)
    at R3Injector.destroy (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:58964:28)
    at NgModuleRef$1.destroy (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:73080:41)
    at C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:77106:56
    at Array.forEach (<anonymous>)
    at PlatformRef.destroy (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:77106:31)
    at complete (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:93213:26)
    at C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:93217:24

When i remove or comment the code hereinafter, i can succeed to to reload a page,

  ngOnDestroy() {
    //this.subscription.unsubscribe();
  }

but i got in the code this new error

ERROR NetworkError
    at XMLHttpRequest.send (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:521132:19)
    at Observable._subscribe (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:13619:17)
    at Observable._trySubscribe (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:504773:25)
    at Observable.subscribe (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:504759:22)
    at scheduleTask (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:92458:32)
    at Observable._subscribe (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:92496:13)
    at Observable._trySubscribe (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:504773:25)
    at Observable.subscribe (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:504759:22)
    at innerSubscribe (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:505776:23)
    at MergeMapSubscriber._innerSub (C:\Users\koste\OneDrive\Documents\Gara\front end\gara-web\dist\gara-app\server\main.js:510200:98)

Please how could i correct it ?
Whithout ssr it is working perfectly. What is the cause of the issue ? Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

友谊不毕业 2025-01-26 04:26:15

ngOnDestroy

在 Angular 销毁指令/组件之前进行清理。取消订阅可观察对象并分离事件处理程序以避免内存泄漏。

在 Angular 销毁指令/组件之前调用。

从你的代码中我无法告诉你什么是取消订阅,也许你在全球范围内取消订阅,如果有时在SSR中你也必须告诉Angular它的平台浏览器,因为你可能正在取消订阅一些使用localStorage或cookies等的服务。当您遇到此类问题时,我也建议使用它。

import { PLATFORM_ID } from "@angular/core";
import { isPlatformBrowser } from '@angular/common';

constructor(@Inject(PLATFORM_ID) private platformId: Object) { }


ngOnDestroy() {
  if (isPlatformBrowser(this.platformId)) {
    this.subscription.unsubscribe();
   }
  }

在某些其他情况下,如果您使用某些插件等,则必须在 server.ts 中声明它们,例如:

server.ts

function setBrowserGlobals(distFolder) {
  const template = readFileSync(join(distFolder, 'index.html')).toString();
  const domino = require('domino');
  const win = domino.createWindow(template);
  global['window'] = win;
 // custom plugin cookieconsent
  global['window']['cookieconsent'] = {
    initialise: function () {
      //
    }
  };
}

export function app(): express.Express {
 const server = express();
  const distFolder = join(process.cwd(), 'dist/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
  setBrowserGlobals(distFolder);
...

}

ngOnDestroy

Cleanup just before Angular destroys the directive/component. Unsubscribe observables and detach event handlers to avoid memory leaks.

Called just before Angular destroys the directive/component.

From your code i can´t tell what are Unsubscribing maybe you are Unsubscribing globally, if that the case sometimes in SSR you have too tell angular its plataform browser, because you may being Unsubscribing some services that uses localStorage or cookies ect. I recomend too use it when u have issues like this.

import { PLATFORM_ID } from "@angular/core";
import { isPlatformBrowser } from '@angular/common';

constructor(@Inject(PLATFORM_ID) private platformId: Object) { }


ngOnDestroy() {
  if (isPlatformBrowser(this.platformId)) {
    this.subscription.unsubscribe();
   }
  }

and in some other cases if you are using some plugins ect you have to declare them at server.ts ex:

server.ts

function setBrowserGlobals(distFolder) {
  const template = readFileSync(join(distFolder, 'index.html')).toString();
  const domino = require('domino');
  const win = domino.createWindow(template);
  global['window'] = win;
 // custom plugin cookieconsent
  global['window']['cookieconsent'] = {
    initialise: function () {
      //
    }
  };
}

export function app(): express.Express {
 const server = express();
  const distFolder = join(process.cwd(), 'dist/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
  setBrowserGlobals(distFolder);
...

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文