Я создал контактную форму, используя Angular во внешнем интерфейсе и nodeJs и nodemailer в бэкэнде, где после отправки формы страница должна перенаправляться на страницу по умолчанию, установленную в приложении. Но вместо этого он не перенаправляет назад и остается только на странице контактов, хотя почта отправляется, как и ожидалось. Кажется, что, хотя данные и проходят, как и ожидалось, в бэкэнде, по какой-то причине в angular ничего не возвращается как данные в методе подписки. Вот почему код перенаправления не выполняется, и через некоторое время он превращается в блок ошибок и затем возвращается на домашнюю страницу по умолчанию. Как я могу это исправить ???
contact component.ts:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { ToastrManager } from 'ng6-toastr-notifications';
@Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.css']
})
export class ContactComponent implements OnInit {
contactForm: FormGroup;
public formName: string;
public formEmail: string;
public formPhone: number;
public formMessage: string;
constructor(private router: Router, private _http:HttpClient,
private formBuilder: FormBuilder, private toastr: ToastrManager) { }
ngOnInit() {
this.contactForm = this.formBuilder.group({
formName: ['', Validators.required],
formEmail: ['', Validators.required],
formPhone: ['', Validators.required],
formMessage: ['']
})}
public contact() {
let param = {
'name': this.contactForm.get('formName').value,
'email': this.contactForm.get('formEmail').value,
'phone': this.contactForm.get('formPhone').value,
'message': this.contactForm.get('formMessage').value,
}
this._http.post('http://localhost:4000/api/v1/blogs' + '/send/mail', param ).subscribe(
data => {
console.log(data) //nothing is coming in data although mail is getting sent
this.toastr.successToastr('Your contact information is saved Susseccfully!', 'Success!');
setTimeout(() =>{
this.router.navigate(['/']);
}, 1000)
},
error => { //navigating to this error block after sometime
console.log(error);
console.log(error.errorMessage);
this.toastr.errorToastr('This is not good!', 'Oops!');
this.router.navigate(['/']);
})}}
бэкэнд узла:
app.post('http://localhost:4000'+'/send/mail', (req, res) => {
let user = {
name: req.body.name,
email: req.body.email,
phone: req.body.phone,
message: req.body.message
}
//nodemailer setup
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'mailid',
pass: 'passkey'
}
});
var mailOptions = {
from: 'mailid',
to: 'mailid',
subject: 'A contact has Arrived!',
html: `<p>Name: ${user.name}</p>
<p>Email: ${user.email}</p>
<p>Phone: ${user.phone}</p>
<p>Message: ${user.message}</p>`};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
console.log(req.body)
});
app.routing:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './client/home/home.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
const routes: Routes = [
{path: '', component: HomeComponent},
{path: 'home', component: HomeComponent},
{path: '**', component: PageNotFoundComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
маршрутизация на стороне клиента:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { BlogHomeComponent } from '../blog-home/blog-home.component';
import { BlogDetailComponent } from '../blog-detail/blog-detail.component';
import { BlogByCategoryComponent } from '../blog-by-category/blog-by-category.component';
import { ContactComponent } from '../contact/contact.component';
const routes: Routes = [
{path: 'blogs', component: BlogHomeComponent},
{path: 'blog/:blogId', component: BlogDetailComponent},
{path: 'bycategory/:categoryId', component: BlogByCategoryComponent},
{path: 'contact', component: ContactComponent}];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ClientRoutingModule { }