Clément Dubois
Clément Dubois

Reputation: 21

How do I use a js method in a ts file?

I am on a project consisting in developping a website with some APIs. I want to use js methods in typescript in order to know when the user click on the button send (send a commentary) to collect information and show them in a another section.

Here's the js code :

const express = require('express');

const mongoose = require('mongoose');
const Thing = require('./models/Thing');

mongoose.connect('mongodb+noemie_farizon://jimbob:[email protected]/test?retryWrites=true&w=majority',
  { useNewUrlParser: true,
    useUnifiedTopology: true })
  .then(() => console.log('Connexion à MongoDB réussie !'))
  .catch(() => console.log('Connexion à MongoDB échouée !'));

const app = express();

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
  next();
});

// middlewear pour enregister un commentaire d'utilisateur
app.post('/api', (req, res, next) => {
  const thing =  new Thing({
     ...req.body
  });
  thing.save()
      .then(() => res.status(201).json({message: 'Objet enregistré !'}))// 201 = code création reussi
      .catch(error => res.status(400).json({ error }));// 400 = code erreur
  next();
});

// affichage des commentaires
app.use('/api', (req, res, next) => {
  // methode en allant chercher dans la bdd
  Thing.find()
      .then(avis => res.status(200).json(avis))
      .catch(error => res.status(400).json({ error }));
});

// pour faire les palmares des pilotes
app.use('/api', (req, res, next) => {
  Thing.find()
      .then(meilleur => res.status(200).json(meilleur))
      .catch(error => res.status(400).json({ error }));
  next();
});

module.exports = app;

and the place where i want to use these methods :

import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';
import { Button } from 'protractor';

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

  constructor() { }

  ngOnInit(): void {
  }

  sendCommentary(){

  }

}

Upvotes: 1

Views: 64

Answers (2)

Hugo Noro
Hugo Noro

Reputation: 3243

Your question is misleading for several reasons.

  1. First there’s a clear misconception that TypeScript and JavaScript are two separate different technologies. They are not. TypeScript supersedes JavaScript by adding a a few additional elements like strong types. You can always run vanilla JavaScript inside a TypeScript file. They are the same underlying technology.
  2. Second the goal you are actually trying to achieve doesn’t make much sense and again seems a bit confused. You are trying to invoke server side code methods in client side code components. That’s not how server and client communication works. You will need to expose an API and endpoints will expose which ever calls you want to do between client and server.

I would suggest you would do a bit of investigation around how to build node express.js APIs and Angular integration. That might clarify some ideas.

Upvotes: 1

Markus Anetz
Markus Anetz

Reputation: 80

You need to separate between "Client" and "Server". Expressjs (first code snippet) is the server part, which provides the API and (probably?) hosts your Angular page (=client, second code snippet).

So there is basically no direct connection between those two applications, except the option to communicate via http(s).

You can have a look at the Angular tutorial how to implement API calls: https://angular.io/guide/http

Upvotes: 0

Related Questions