簡體   English   中英

如何在 Node.Js 中將 Angular 組件渲染為 HTML(發送電子郵件)

[英]How to Render an Angular Component to HTML in Node.Js (To Send EMails)

假設我有一個簡單的 Angular 組件:

@Component({
  selector: 'app-email-content',
  template: '<h1>Welcome {{username}}!</h1>'
})
export class WelcomeEmailComponent {
  @Input() username: string
}

我的目標是使用這個 Angular 組件並使用 Node.Js 將其呈現為普通的 HTML,以發送自定義的電子郵件。

我知道服務器端渲染絕對可以使用Angular Universal 但我不確定如何顯式呈現一個特定組件。

做法是從Angular SSR項目向用戶email發送一個Angular基於組件的動態生成模板。

在這個答案的底部找到示例存儲庫。

您需要遵循的步驟;

  1. 在專用於僅顯示 email 模板而不是導航欄、全局 CSS 等的單獨路由路徑中設計您的模板。

例子:

歡迎電子郵件-component.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-welcome-email-component',
  templateUrl: './welcome-email-component.component.html',
  styleUrls: ['./welcome-email-component.component.css']
})
export class WelcomeEmailComponentComponent implements OnInit {

  username: any;

  constructor(private route: ActivatedRoute) { }

  ngOnInit(): void {
    this.route.params.subscribe(params => {
      this.username = params.username;
    });
  }

}

歡迎電子郵件-component.component.html

<style>
    .title-p {
        color: #00025a;
        font-size: 20px;
        font-weight: bold;
    }
</style>

<p class="title-p">Welcome {{username}}</p>

您需要為該組件指定一個路由,如下所示,因此當用戶導航到welcome-email/username路由時,它應該只顯示 email 模板生成的組件。

{ path: 'welcome-email/:username', component: WelcomeEmailComponentComponent }
  1. 根據偉大的 Angular SSR 指南,使用 Angular Universal將 Angular SSR 實施到您的項目。

這只是兩行代碼。

ng add @nguniversal/express-engine
npm run dev:ssr
  1. 最后創建一個服務器端 API 以從您的 Angular 組件生成模板並發送電子郵件或提供單個組件的 HTML 代碼,將 API function 添加到您的server.ts中,如下所示。

服務器.ts

server.get('/api/send-email/:username', (req, res) => {
    // Below is the URL route for the Angular welcome mail component
    request(`http://127.0.0.1:4200/welcome-email/${req.params.username}`, (error, response, body) => {
        // TODO : Send email to the user from WelcomeEmailComponentComponent.ts component as `body`
        // use the body to send email
        res.send('Email sent');
    });
});

示例代碼: https://github.com/aslamanver/angular-send-component-email

在此存儲庫上動態生成的組件的演示;

在此處輸入圖像描述

最后,當您訪問/api/send-email/:username時,這將生成歡迎郵件組件並提供 HTML 正文,此后您可以繼續您的 email 發送 function。

我鼓掌@Googlian 的回答。 但是,angular 產生了太多不熟悉的 HTML5、CSS3 和 angular 特定的捆綁功能,因此之后,如果您想要真正有效的 email 內容,則必須一一刪除這些內容,否則您的 8838851837012 將被視為垃圾郵件客戶端 mailbuclient81837012

我建議您擁有一個具有 xHTML 標准的組件,該組件具有無 CSS3、無實驗性 HTML5 功能,並使用thisElementRef構建一個 email 模板,然后手動解析所需字段。

將字符串發送到服務器端,nodejs,然后將其作為 email 發送。您可以使用 nodemailer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM