Search code examples
javascriptnode.jsangularangular2-services

How to create an object in Node js backend server and pass it to Angular 2 front end


I want to form an javascript object at node server and example : below is the object present in my server.js file

chart = {property: value, property: value, property: value}

I want to fetch same object in angular 2 service which is injected to a component.

Please suggest how can I achieve the same?


Solution

  • Use the Httpclient of angular. Here is an example:

    Service:

    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';
    import { HttpClient } from '@angular/common/http';
    
    @Injectable()
    export class RegisterService {
    
      constructor(private http: HttpClient) {
    
      }
    
      register(username: string, randomPass: string, email: string): Observable<any> {
        return this.http.post('http://localhost:3000/register',
          {username: username, randomPass: randomPass, email: email})
        .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
      }
    }
    

    In our service we injected the HttpClient which is an abstraction layer over AJAX which Angular provides for us. This service makes a post request with the following code this.http.post. This function takes two arguments, the URL to which the POST request is sent, and the keyvalue pairs in the body of the POST request. The function returns an Observable which can be subscribed to in the component which uses this function.

    Register component (only register function):

     public register(username: string, randomPass: string, email: string) {
          this.registerService.register(username, email)
            .subscribe(myResponse => {
              if (myResponse.success) {
                this.registered = true;
            });
        }
      }
    

    This function should be called when we want to make the AJAX request. It uses dependency inversion principle, this way we can alter the service without having to alter the component drastically.

    NodeJS express Backend

    I suppose you already have a basic express app running then this is the middleware you need to listen to the AJAX call and respond with the object which you want to send.

    app.post('register', (req, res, next) => {
       chart = {property: value, property: value, property: value}
    
       return res.json(chart);
    });
    

    This middleware (part of express framework) listens to POST requests on the register component. It then sends a JSON response with the values of the chart object.

    If anything is not clear I strongly suggest that you try to grasp the principle of read some articles about the topic.