我遇到一个问题,我无法编译引用浏览器api的打字稿代码。即localStorage
。该项目使用Angular 2和typescript 2.1。我尝试在文件的开头设置一个类型声明,但我仍然收到错误。这是错误:
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"; // JwtProvider's LoginPath
var data = {
username: username,
password: password,
client_id: "OpenGameList",
// required when signing up with username/password
grant_type: "password",
// space-separated list of scopes for which the token is issued
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;
}
// Converts a Json object to urlencoded format
toUrlEncodedString(data: any) {
var body = "";
for (var key in data) {
if (body.length) {
body += "&";
}
body += key + "=";
body += encodeURIComponent(data[key]);
}
return body;
}
// Persist auth into localStorage or removes it if a NULL argument is given
setAuth(auth: any): boolean {
if (auth) {
localStorage.setItem(this.authKey, JSON.stringify(auth));
}
else {
localStorage.removeItem(this.authKey);
}
return true;
}
// Retrieves the auth JSON object (or NULL if none)
getAuth(): any {
var i = localStorage.getItem(this.authKey);
if (i) {
return JSON.parse(i);
}
else {
return null;
}
}
// Returns TRUE if the user is logged in, FALSE otherwise.
isLoggedIn(): boolean {
return localStorage.getItem(this.authKey) != null;
}
}
编辑----
我发现了这个问题。模板项目重新编译服务器上没有localStorage
的角度spa。为了编译它,我必须用以下内容包围它:
import { isBrowser } from 'angular2-universal';
if (isBrowser) {
// Do stuff with localStorage
}