I have chosen to utilize universal-starter as the foundation of my project.
Upon initialization, my application reads a token containing user information from localStorage.
@Injectable()
export class UserService {
foo() {}
bar() {}
loadCurrentUser() {
const token = localStorage.getItem('token');
// additional operations
};
}
Although everything functions properly, I encounter the following error in the server side (terminal) due to server-side rendering:
EXCEPTION: ReferenceError: localStorage is not defined
I came across the idea of using Dependency Injection to address this issue in ng-conf-2016-universal-patterns, but that resource seems outdated.
Currently, I have two files:
main.broswer.ts
export function ngApp() {
return bootstrap(App, [
// ...
UserService
]);
}
main.node.ts
export function ngApp(req, res) {
const config: ExpressEngineConfig = {
// ...
providers: [
// ...
UserService
]
};
res.render('index', config);
}
Both files are using the same UserService. Can anyone provide guidance or code examples on how to implement different Dependency Injection to resolve this?
If there are alternative solutions other than Dependency Injection, those suggestions would also be appreciated.
UPDATE 1 I am utilizing Angular 2 RC4 and attempted @Martin's approach. However, despite importing it, I continue to receive errors in the terminal:
Terminal (npm start)
/my-project/node_modules/@angular/core/src/di/reflective_provider.js:240 throw new reflective_exceptions_1.NoAnnotationError(typeOrFunc, params); ^ Error: Cannot resolve all parameters for 'UserService'(Http, ?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'UserService' is decorated with Injectable.
Terminal (npm run watch)
error TS2304: Cannot find name 'LocalStorage'.
It appears there may be duplication with the LocalStorage
from angular2-universal
even though I haven't used
import { LocalStorage } from 'angular2-universal';
. Even after changing it to LocalStorage2
, the issue persists.
Additionally, my IDE WebStorm indicates errors as well:
https://i.sstatic.net/qKzbs.png
By the way, I found an
import { LocalStorage } from 'angular2-universal';
, but unsure of its usage.
UPDATE 2, I made modifications (not certain if it's the optimal solution):
import { Injectable, Inject } from '@angular/core';
import { Http } from '@angular/http';
import { LocalStorage } from '../../local-storage';
@Injectable()
export class UserService {
constructor (
private _http: Http,
@Inject(LocalStorage) private localStorage) {} // <- this line is new
loadCurrentUser() {
const token = this.localStorage.getItem('token'); // changed from `localStorage` to `this.localStorage`
// …
};
}
This adjustment resolves the problem encountered in UPADAT 1, but now I'm facing an error in the terminal:
EXCEPTION: TypeError: this.localStorage.getItem is not a function