angular / universal-starter

Angular Universal starter kit by @AngularClass
2.02k stars 688 forks source link

Angular services on server side #533

Open fabiolima opened 6 years ago

fabiolima commented 6 years ago

Hi, there is a way to use angular services on server side?

In my server.ts i have an route like this:

app.get('/example/**', ExampleController);

and inside function ExampleController(req, res) { ....

I want to use my DataService but he needs to be injected, right?

So i'm trying this: ... import { Injector } from '@angular/core';

const injector = Injector.create([ { provide: DataService, useClass: DataService, deps: [RestService] }, { provide: RestService, useClass: RestService, deps: [HttpClient] }, { provide: HttpClient, useClass: HttpClient, deps: [HttpHandler] }, { provide: HttpHandler, useClass: ????, deps: []} ]);

But following the dependencies of the dependencies, HttpHandler is an abstract class and cannot fill. Whats missing there? There is a way to inject the whole HttpClientModule and just inject my services??

m98 commented 6 years ago

There is no problem in using services in the server-side. Actually, Angular runs your code both on server, and browser. But sometimes, you need to run a code just on server-side. Then you can specify the platform type.

fabiolima commented 6 years ago

@m98 Thx for reply.

I know about platform type, but I need to use the service inside of Node. On angular, if your service is globally provided you just need do something like: import { Service } from './path' ;

@Component({...}) class MyComponent { constructor(private service: Service) { } }

and the Angular resolves the service dependencies and injects into constructor, but on Node environment I dont know how to use.

Phoscur commented 6 years ago

@fabiolima I think you are comparing Angular Application Serverside Rendering and REST API declaration, in the search of a common denominator. You won't find much. You can reuse your Constants, Functions and Classes undecorated in Angular land. Your example API needs to factor out e.g. validation, so these parts can be reused in serverside and clientside execution.

As I understand it, the application is rendered by the server on every request, you probably do not want to instantiate a new Angular Rendering Process if you want to return JSON data. Also, not being bound to one single request (global) nodejs express scope can have uses for serverside logic (in memory cache, shared sessions).

I have some related questions:

I think the core question of this issue is about seperation of server (database) state and application state on client side and how they possibly synchronise after initial application rendering.