I am having a problem where I cannot compile typescript code that references the api browser. Namely localStorage. The project uses Angular 2 and typescript 2.1. I tried to set the type declaration at the beginning of the file, but I still get the error. Here's the error
:
import { Injectable, EventEmitter } from "@angular/core";
import { Http, Headers, Response, RequestOptions } from "@angular/http";
import { Observable } from "rxjs/Observable";
import { AuthHttp } from "./auth.http";
declare var localStorage: any;
@Injectable()
export class AuthService {
authKey = "auth";
constructor(private http: AuthHttp) {
}
login(username: string, password: string): any {
var url = "api/connect/token";
var data = {
username: username,
password: password,
client_id: "OpenGameList",
grant_type: "password",
scope: "offline_access profile email"
};
return this.http.post(
url,
this.toUrlEncodedString(data),
new RequestOptions({
headers: new Headers({
"Content-Type": "application/x-www-form-urlencoded"
})
}))
.map(response => {
var auth = response.json();
console.log("The following auth JSON object has been received:");
console.log(auth);
this.setAuth(auth);
return auth;
});
}
logout(): boolean {
this.setAuth(null);
return true;
}
toUrlEncodedString(data: any) {
var body = "";
for (var key in data) {
if (body.length) {
body += "&";
}
body += key + "=";
body += encodeURIComponent(data[key]);
}
return body;
}
setAuth(auth: any): boolean {
if (auth) {
localStorage.setItem(this.authKey, JSON.stringify(auth));
}
else {
localStorage.removeItem(this.authKey);
}
return true;
}
getAuth(): any {
var i = localStorage.getItem(this.authKey);
if (i) {
return JSON.parse(i);
}
else {
return null;
}
}
isLoggedIn(): boolean {
return localStorage.getItem(this.authKey) != null;
}
}
EDIT ----
I figured out this problem. The template project recompiles Angular spam on a server where not localStorage. To compile it, I have to surround it with the following:
import { isBrowser } from 'angular2-universal';
if (isBrowser) {
}
source
share