0

I want to use angular 5 and nodeJs in the same folder, so for example the app.component.ts communicate with a file named server.js which contains nodeJs code, if a user enter a value of input in angular the value will be sent in nodeJs file and after running few functions it will send a response, so is this possible? is there a way to bind a var from angular to a var of nodeJs (can we bind a var from Js file to a var from ts file) please note that i'm a begginer

Kaneki Em
  • 13
  • 6

1 Answers1

0

Generally I would split the client side code from the server side code because they are finally "executed"in different locations. This way you keep focused within the context of your client side code (yourapp/client) and server side code (yourapp/server). Client (angular) and server code will then communicate with HTTP calls (HttpClient in Angular and e.g. using Express on the Node side)

The server code (node.js) could look like this (yourapp/server/index.js)

var express = require('express');
var app = express();

app.get('/hello', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

And on the client side (angular), you would need a service yourapp/client/src/app/demo.service.ts like:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable()
export class DemoService {

    constructor(private http:HttpClient) {}

    // Uses http.get() to load data from a single API endpoint
    getHello() {
        return this.http.get('/ello');
    }
}

an in e.g. yourapp/client/src/app/app.component.ts:

import { DemoService } from './demo.service';

meassage: string;

ngOnInit() {
    this.message = this.getHello();
}

The html (yourapp/client/src/app/app.component.html) then could look like:

<h1>Message from Server</h1>
<p>{{message}}</p>

Hope this makes it a little bit clearer

Sebastian Hildebrandt
  • 2,661
  • 1
  • 14
  • 20