How to store token on server side [Angular Universal]

1.4k Views Asked by At

I found this post: https://github.com/angular/universal/issues/272 where user @gdi2290 explain how to add that functionalty

But I get error in my code:

/home/master/Documents/rs-dash/dist/server/server.bundle.js:317 throw new Error("Module build failed: Error: /home/master/Documents/rs-dash/src/app/app.node.module.ts (97,48): Property 'injector' does not exist on type 'ApplicationRef'.)\n/home/master/Documents/rs-dash/src/app/app.node.module.ts (97,61): Cannot find name 'YourServiceWithState'.)\n at _checkDiagnostics (/home/master/Documents/universal-cli/packages/@ngtools/webpack/src/loader.ts:115:15)\n at /home/master/Documents/universal-cli/packages/@ngtools/webpack/src/loader.ts:140:17"); ^

I added in node module:

constructor(public appRef: ApplicationRef) {

    }
    // lives in your node main module
    universalDoDehydrate(universalCache) {
        var yourServiceWithState = this.appRef.injector.get(YourServiceWithState)
        var key = 'yourServiceWithState._state'
        universalCache[key] = yourServiceWithState._state.justOneProp
    }

and in browser module:

constructor(public appRef: ApplicationRef) {
        // lives in your browser main module
        var key = 'yourServiceWithState._state'
        if (UNIVERSAL_CACHE[key]) {
            localStorage[key] = UNIVERSAL_CACHE[key]
        }
    }

Anyone know what is problem, I am using universal-cli?

1

There are 1 best solutions below

7
Burak Tasci On

I had the issue and developed a cache & server-side solution for it (4 separate packages for cache operations both on server and browser platforms).

Check the implementation at ng-seed/universal. Everything is handled via the @Cached(...) decorator on the method/loader/etc which you want it to be cached. Also, there's the possibility to use caching methods (has, get, set) using the caching API.

Here are the packages you need to use, for server-side caching: