2

I am new to Angular5. I need to pass user details from angular to nodejs.

app.component.ts:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl, FormArray } from 
'@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    constructor(private http:Http) { } 
    onSubmit(registerForm) {
       console.log(registerForm.value);
       let url = 'http://localhost:8080/signup';
       this.http.post(url, {registerForm(registerForm)}).subscribe(res => 
          console.log(res.json()));
    }
 }

Now I need to pass those data to nodejs routes to proceed further.

Node js routing file:

module.exports = function(app, passport) {

app.post('/signup', passport.authenticate('local-signup', {
    successRedirect : '/', 
    failureRedirect : '/',
    failureFlash : true 
}));

}; 

Now am getting the following error: Uncaught Error: Can't resolve all parameters for AppComponent: (?).

4
  • Please post your HTML content also Commented Mar 29, 2018 at 5:12
  • still, struggling ? or you got the answer? Commented Mar 29, 2018 at 10:46
  • @NikhilSavaliya please find my updated post. Getting errors. Commented Mar 29, 2018 at 10:49
  • @NikhilSavaliya here is the html form am posting: <form #registerForm="ngForm" (ngSubmit)="onSubmit(registerForm)"> Commented Mar 29, 2018 at 10:52

3 Answers 3

1

Call Your function from the component.html file it will trigger the function which will be in your component.ts file. From this function call service which contains the function which will be requesting your node API

addData() {
    this.adminService.addCountry(this.form.value).subscribe(
      res => {
        var response = res.json();
        this.flashMessagesService.show(response.message, {
          cssClass: "alert-success",
          timeout: 2000
        });
      },
      error => {
        if (error.status == 401) {
          localStorage.removeItem("currentUser");
          this.router.navigate(["/"]);
        } else {
          this.flashMessagesService.show(error.json().error, {
            cssClass: "alert-danger",
            timeout: 2000
          });
        }
      }
    );
  }

Create admin service to call your HTTP URL which is running on node

Service

  addCountry(formData) {
    console.log(formData);
    var authToken = this.getAuthToken();
    if (authToken != "") {
      var headers = this.getHeaders();
      headers.append("Authorization", authToken);
      return this.http
        .post(
          `http://localhost:3000/addData`,
          this.formData(formData),
          { headers: headers }
        )
        .map((response: Response) => {
          return response;
        });
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

0

You can use service in angular to send data to nodeJs. Please refer the tutorials of Angular from Codecraft. Please have a look at https://codecraft.tv/courses/angular/http/core-http-api/

For now you need to send some registration form data. So 1. import http module to AppModule 2. Refer to the documentation above 3. You can pass data to nodejs using a POST method of http

Comments

0

I think you should look on Observable. https://angular.io/guide/observables

On logic you should create server with Observable request to your NodeJs (express) app. Then you can add to your component function with subscribe.

Some code:

Create authentication service

ng generate service authentication

Create user service for store user data (or you can only store it in other components)

ng generate service user

On authentication.service.ts create authenticate method

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { UserService } from '../user/user.service';
import { Router } from '@angular/router';`

@Injectable()
export class AuthenticationService {
  token: string;

  constructor(private router: Router, private httpClient: HttpClient, 
   public userService: UserService) {
     const currentUser = JSON.parse(localStorage.getItem('currentUser'));
     this.token = currentUser && currentUser.token;
  }

  getToken(email: string, password: string): Observable<User> {
     return this.httpClient.post<User>(apiRoutes.authentication, 
     {userEmail: email, userPassword: password});
  }

  authenticate(email: string, password: string) {
    this.getToken(email, password).subscribe(response => {
      if (response.userToken.length > 0) {
        this.userService.user.userEmail = response.userEmail;
        this.userService.user.userToken = response.userToken;
        this.userService.user._id = response._id;
        this.userService.user.isUserAuthenticated = true;
        localStorage.setItem('currentUser', JSON.stringify({token: response.userToken}));
        this.router.navigate(['/']);
       // TODO: Need some error logic
    } else {
      return false;
    }
  });
}

Now you can add to your form in template

<form (ngSubmit)="this.authenticationService.authenticate(userEmail, password)">
...
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.